2021-01-24 00:18:56 +01:00
|
|
|
# Given a number, find sum of its digits.
|
2021-01-22 09:58:42 +01:00
|
|
|
|
2021-01-24 00:18:56 +01:00
|
|
|
def digits_sum(n)
|
2021-02-07 08:05:54 +01:00
|
|
|
a = 0
|
|
|
|
sum = 0
|
2021-01-22 09:58:42 +01:00
|
|
|
until n.zero?
|
|
|
|
a = n % 10
|
|
|
|
sum += a
|
|
|
|
n /= 10
|
|
|
|
end
|
2021-02-07 08:05:54 +01:00
|
|
|
sum
|
2021-01-22 09:58:42 +01:00
|
|
|
end
|
|
|
|
|
2021-02-07 08:05:54 +01:00
|
|
|
puts 'Sum of digits of 3456 is ' + digits_sum(3456).to_s
|
2021-01-22 09:58:42 +01:00
|
|
|
# Sum of digits of 3456 is 18
|
2021-02-07 08:05:54 +01:00
|
|
|
puts 'Sum of digits of 1234 is ' + digits_sum(1234).to_s
|
2021-01-22 09:58:42 +01:00
|
|
|
# Sum of digits of 1234 is 10
|
2021-02-07 08:05:54 +01:00
|
|
|
puts 'Sum of digits of 9251321 is ' + digits_sum(9_251_321).to_s
|
2021-01-22 09:58:42 +01:00
|
|
|
# Sum of digits of 9251321 is 23
|