0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

整数の桁を数値として取得する

Posted at

思考プロセス

「取得したい桁を末尾に移動させ、余りとして取得する」

任意の整数を10で割った余りを求めることで、末尾の桁を1つ取得する。
1つ上の桁を取得するには、10で割った整数部分を抜き出すことで末尾に移動させることができ、同じように1つの数値のみを取得できる。

73から3を取得する

10で割った余りは「%」で表せる。

num = 73
last_digit = num % 10  # 末尾の桁を取得
print(last_digit)  # 3

73から7を取得する

「//」で割ることで、余りを切り捨てられる。

num = 73
first_digit = num // 10  # 先頭の桁を取得
print(first_digit)  # 7

735から3を取得する

3を末尾の桁に移動させたい。上2つの作業を応用することで、真ん中の桁を取得できる。

num = 735
second_digit = (num // 10) % 10  # 十の位を取得
print(second_digit)  # 3

ループ処理で全ての桁を分割して数値を取得し、足し合わせる

末尾から1つずつ桁を増やして数値を取得し、合算する処理を行う。先ほどの処理をループで繰り返すことで、全ての桁を取得することができる。

total = 0 で初期値を格納

num = 735755
total = 0  # 合計値を保持

num = 735755はループ処理の度に末尾の桁を削除するので、ループ条件はnum > 0

while num > 0:
    total += num % 10  # 1の位の数字を加算
    num //= 10  # 右端の桁を削除

結果を出力する

print(total)  # 7 + 3 + 5 + 7 + 5 + 5 = 32 となり、32 が出力
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?