題目看起來好理解,想下及翻閱 API 後,
透過組合技便能完成題目。
Codewars LV6
題目(Write Number in Expanded Form):
1
2
3
4
5
6
7Write Number in Expanded Form
You will be given a number and you will need to return it as a string in Expanded Form. For example:
expanded_form(12); # Should return '10 + 2'
expanded_form(42); # Should return '40 + 2'
expanded_form(70304); # Should return '70000 + 300 + 4'
NOTE: All numbers will be whole numbers greater than 0.
1
2
3
4
5
6
7
8
9def expanded_form(num)
# Your code here
end
it "Example cases" do
Test.assert_equals(expanded_form(12), '10 + 2')
Test.assert_equals(expanded_form(42), '40 + 2')
Test.assert_equals(expanded_form(70304), '70000 + 300 + 4')
end
影片解題:
答案:
1
2
3
4
5
6
7
8
9# Write Number in Expanded Form
def expanded_form(num)
num.to_s
.reverse
.chars
.map.with_index{| x, i | x == '0' ? nil : x + '0' * i }.compact
.reverse
.join' + '
end
本文同步發布於 小菜的 Blog https://riverye.com/