Merge pull request #101 from jsca-kwok/jk-add-digits

Add Digits Algorithm
This commit is contained in:
Vitor Oliveira 2021-03-18 16:45:53 -07:00 committed by GitHub
commit 50b20705b9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 62 additions and 0 deletions

View file

@ -4,6 +4,7 @@
## Data Structures ## Data Structures
* Arrays * Arrays
* [Add Digits](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/add_digits.rb)
* [Find All Duplicates In An Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/find_all_duplicates_in_an_array.rb) * [Find All Duplicates In An Array](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/find_all_duplicates_in_an_array.rb)
* [Find The Highest Altitude](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/find_the_highest_altitude.rb) * [Find The Highest Altitude](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/find_the_highest_altitude.rb)
* [Get Products Of All Other Elements](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/get_products_of_all_other_elements.rb) * [Get Products Of All Other Elements](https://github.com/TheAlgorithms/Ruby/blob/master/data_structures/arrays/get_products_of_all_other_elements.rb)

View file

@ -0,0 +1,61 @@
# 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}
#
# 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))
# # => 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
puts(add_digits(284))
# => 5