你必須很努力

Day24 - Codewars 刷題

2019/10/03
字數統計: 166閱讀時間: 1 min

題目看起來好理解,想下及翻閱 API 後,
透過組合技便能完成題目。

Codewars LV6


題目(Write Number in Expanded Form)

1
2
3
4
5
6
7
Write 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
9
def 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/

原文連結:https://riverye.com/2019/10/03/Day24-Codewars-刷題/

發表日期:2019-10-03

更新日期:2022-12-21

CATALOG