Created
July 26, 2012 01:46
-
-
Save t11a/3179789 to your computer and use it in GitHub Desktop.
sum of digits
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### solution 1 | |
def sum_of_digits n | |
n.to_s.split('').inject(0) {|sum, i| sum + i.to_i} | |
end | |
### solution 2 | |
def sum_of_digits n | |
sum = 0 | |
while n > 0 do | |
d = n / 10 | |
r = n % 10 | |
sum += r | |
n -= r | |
n /= 10 if d > 0 | |
end | |
sum | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment