From fd3add587c806cc511eaa36265597108b15c8765 Mon Sep 17 00:00:00 2001 From: Jessica Kwok Date: Thu, 18 Mar 2021 13:15:19 -0700 Subject: [PATCH] Add solution without recursion --- data_structures/arrays/add_digits.rb | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/data_structures/arrays/add_digits.rb b/data_structures/arrays/add_digits.rb index e18d768..731236d 100644 --- a/data_structures/arrays/add_digits.rb +++ b/data_structures/arrays/add_digits.rb @@ -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