Merge pull request #102 from TheAlgorithms/add-sum-digits-different-approach

Add Digits: mathematical - digital root approach
This commit is contained in:
Vitor Oliveira 2021-03-18 17:10:04 -07:00 committed by GitHub
commit fdfb4fff55
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 39 additions and 3 deletions

View file

@ -40,6 +40,7 @@
## Maths
* [Abs](https://github.com/TheAlgorithms/Ruby/blob/master/maths/abs.rb)
* [Abs Test](https://github.com/TheAlgorithms/Ruby/blob/master/maths/abs_test.rb)
* [Add Digits](https://github.com/TheAlgorithms/Ruby/blob/master/maths/add_digits.rb)
* [Aliquot Sum](https://github.com/TheAlgorithms/Ruby/blob/master/maths/aliquot_sum.rb)
* [Aliquot Sum Test](https://github.com/TheAlgorithms/Ruby/blob/master/maths/aliquot_sum_test.rb)
* [Binary To Decimal](https://github.com/TheAlgorithms/Ruby/blob/master/maths/binary_to_decimal.rb)

View file

@ -33,10 +33,10 @@ def add_digits(num)
add_digits(sum)
end
# puts(add_digits(38))
puts(add_digits(38))
# # => 2
# puts(add_digits(284))
puts(add_digits(284))
# # => 5
#
@ -58,4 +58,4 @@ puts(add_digits(38))
# => 2
puts(add_digits(284))
# => 5
# => 5

35
maths/add_digits.rb Normal file
View file

@ -0,0 +1,35 @@
# 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: 3 + 8 = 11, 1 + 1 = 2.
#
# Approach: Mathematical: Digital Root
#
# https://en.wikipedia.org/wiki/Digital_root
# https://brilliant.org/wiki/digital-root/
#
#
# Complexity Analysis
#
# Time Complexity: O(1).
# Space Complexity: O(1).
def add_digits(num)
return 0 if num == 0
return 9 if num % 9 == 0
num % 9
end
puts(add_digits(38))
# # => 2
puts(add_digits(284))
# # => 5