mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-01-13 08:01:03 +01:00
Add recursion solution
This commit is contained in:
parent
899eaf1d3a
commit
5588587bc1
1 changed files with 18 additions and 2 deletions
|
@ -15,10 +15,26 @@
|
|||
# @return {Integer}
|
||||
|
||||
#
|
||||
# Approach 1: Brute Force
|
||||
# Approach 1: Recursion
|
||||
#
|
||||
# Time complexity: O(n)
|
||||
#
|
||||
def add_digits(num)
|
||||
if num.to_s.length < 2
|
||||
return num
|
||||
end
|
||||
|
||||
digits_to_sum = num.to_s.split('')
|
||||
sum = 0
|
||||
digits_to_sum.each do |num|
|
||||
sum += num.to_i
|
||||
end
|
||||
|
||||
add_digits(sum)
|
||||
end
|
||||
|
||||
puts(add_digits(38))
|
||||
# Output: 2
|
||||
# => 2
|
||||
|
||||
puts(add_digits(284))
|
||||
# => 5
|
Loading…
Reference in a new issue