mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-02-05 08:46:12 +01:00
Merge pull request #102 from TheAlgorithms/add-sum-digits-different-approach
Add Digits: mathematical - digital root approach
This commit is contained in:
commit
fdfb4fff55
3 changed files with 39 additions and 3 deletions
|
@ -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)
|
||||
|
|
|
@ -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
35
maths/add_digits.rb
Normal 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
|
Loading…
Add table
Reference in a new issue