As the title says This is the output of how to extract the hundreds, tens, and ones digits from a three-digit integer.
The remainder of the calculation result of dividing an integer by 100 and then dividing it by 10 is the hundreds digit.
num = 345
result_100 = (num / 100) % 10
puts result_100
# => 3
If you do (num / 100) normally, it will be 3.45, In the case of Ruby, since integer / integer = integer (rounded down to the nearest whole number) (num / 100) becomes 3.
The remainder of the calculation result of dividing an integer by 10 and then dividing it by 10 is the tens digit.
num = 345
result_10 = (num / 10) % 10
puts result_10
# => 4
(num / 10) is 34, and when 34 is divided by 10, the remainder is 4.
The remainder of the calculation result of dividing an integer by 10 is the ones place.
num = 345
result_1 = num % 10
puts result_1
# => 5
If you want to extract the thousands digit with a 4-digit number
It becomes (num / 1000)% 10
. Hundreds, tens, and ones are calculated in the same way as above.
Recommended Posts