-
-
Save rafaeljesus/84a145f358c50cd23df9 to your computer and use it in GitHub Desktop.
codewars exemple
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
#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