Skip to content

Instantly share code, notes, and snippets.

@Micka33
Created January 28, 2014 14:58
Show Gist options
  • Save Micka33/8669111 to your computer and use it in GitHub Desktop.
Save Micka33/8669111 to your computer and use it in GitHub Desktop.
codewars exemple
#Subject
#Find the sum of the digits of all the numbers from 1 to N (both ends included).
#For N = 10 the sum is 1+2+3+4+5+6+7+8+9+(1+0) = 46
#For N = 11 the sum is 1+2+3+4+5+6+7+8+9+(1+0)+(1+1) = 48
#For N = 12 the sum is 1+2+3+4+5+6+7+8+9+(1+0)+(1+1) +(1+2)= 51
#Supported Ruby version is 1.9.3
#Tests
it 'should' do
Test.assert_equals(solution(10), 46)
Test.assert_equals(solution(11), 48)
Test.assert_equals(solution(12), 51)
Test.assert_equals(solution('12'), 51)
Test.assert_equals(solution( 0 ), 0)
Test.assert_equals(solution(1), 1)
end
#Basic solution
def solution(n)
sum = 0
(1..n.to_i).each do |c|
c.to_s.chars.each do |i|
sum += i.to_i
end
end
sum
end
#Optimal solution
def solution(n)
("1".."#{n}").to_a.join.chars.map(&:to_i).inject(&:+)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment