Skip to content

Instantly share code, notes, and snippets.

@t11a
Created July 26, 2012 01:46
Show Gist options
  • Save t11a/3179789 to your computer and use it in GitHub Desktop.
Save t11a/3179789 to your computer and use it in GitHub Desktop.
sum of digits
### 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