TheAlgorithms-Ruby/data_structures/arrays/add_digits.rb

60 lines
987 B
Ruby
Raw Normal View History

2021-03-17 16:17:08 +01:00
# Challenge name: Add Digits
#
# Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
#
# Example:
#
# Input: 38
# Output: 2
# Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
# Since 2 has only one digit, return it.
#
# Follow up:
# Could you do it without any loop/recursion in O(1) runtime?
# @param {Integer} num
# @return {Integer}
#
2021-03-18 16:55:05 +01:00
# Approach 1: Recursion
#
# Time complexity: O(n)
2021-03-17 16:17:08 +01:00
#
def add_digits(num)
2021-09-03 22:24:58 +02:00
return num if num.to_s.length < 2
2021-03-18 16:55:05 +01:00
digits_to_sum = num.to_s.split('')
sum = 0
digits_to_sum.each do |num|
sum += num.to_i
end
add_digits(sum)
2021-03-17 16:17:08 +01:00
end
2021-03-19 01:00:54 +01:00
puts(add_digits(38))
2021-03-18 21:15:19 +01:00
# # => 2
2021-03-19 01:00:54 +01:00
puts(add_digits(284))
2021-03-18 21:15:19 +01:00
# # => 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
2021-03-17 16:17:08 +01:00
puts(add_digits(38))
2021-03-18 16:55:05 +01:00
# => 2
puts(add_digits(284))
2021-03-19 01:00:54 +01:00
# => 5