1
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?

More than 3 years have passed since last update.

整数のそれぞれの桁の数字を求める

1
Last updated at Posted at 2022-01-17

学習したことのアウトプットとして

勉強をしていると「3桁のそれぞれの桁の数字を足すプログラムの作成」というものがあった。
今まで桁を取り出す方法とか考えたことがなく、勉強になったため記事にしてみる。

それぞれの桁の数字の取り出し方

num = 3456

# 千の位
result_1000 = (num / 1000) % 10
# 百の位
result_100 = (num / 100) % 10
# 十の位
result_10 = (num / 10) % 10
# 一の位
result_1 = (num / 1) % 10

puts result_1000 # => 3
puts result_100  # => 4
puts result_10   # => 5
puts result_1    # => 6

ちなみに

一万の位の場合は
(num/10000) % 10 で取り出すことが可能。

以上。法則は分かりやすいので特別難しいことはないかと。

追記(20230118)

コメントで教えていただいたことを追記しときます。
(教えていただき有難うございます!)

digitsメソッド

表記した数値を配列で返してくれる

# 整数を定義
irb(main):001:0> num = 123456
=> 123456
# 配列として帰ってくる
irb(main):002:0> num.digits
=> [6, 5, 4, 3, 2, 1]

非負整数でなければいけない。非負整数でない場合はエラーが発生する。

文字列として考える

to_sメソッドを使用する。to_sメソッドは文字列以外のオブジェクトを文字列に変換するメソッド。

num = 1234
# 頭からn桁目を指定して取り出せる
puts num.to_s[0]  #1
puts num.to_s[1]  #2
puts num.to_s[2]  #3
puts num.to_s[3]  #4

# 末尾からn桁目みたいな書き方をする場合
puts num.to_s[-1]  #4
puts num.to_s[-2]  #3

 

こうしてみるとコードの書き方や考え方ってたくさんあるなぁと…
そこが難しくもあるし、奥深いなと感じた。

※補足等ありましたらコメントいただけると幸いです。

1
0
2

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
1
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?