mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-26 21:58:56 +01:00
Add solution without recursion
This commit is contained in:
parent
5588587bc1
commit
fd3add587c
1 changed files with 21 additions and 0 deletions
|
@ -33,6 +33,27 @@ def add_digits(num)
|
|||
add_digits(sum)
|
||||
end
|
||||
|
||||
# puts(add_digits(38))
|
||||
# # => 2
|
||||
|
||||
# puts(add_digits(284))
|
||||
# # => 5
|
||||
|
||||
#
|
||||
# Approach 2: Without recursion
|
||||
#
|
||||
def add_digits(num)
|
||||
until num.to_s.length < 2
|
||||
digits_to_sum = num.to_s.split('')
|
||||
num = 0
|
||||
|
||||
digits_to_sum.each do |number|
|
||||
num += number.to_i
|
||||
end
|
||||
end
|
||||
num
|
||||
end
|
||||
|
||||
puts(add_digits(38))
|
||||
# => 2
|
||||
|
||||
|
|
Loading…
Reference in a new issue