iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 24
1
自我挑戰組

自我挑戰 Ruby 刷題 30 天系列 第 24

Day24 - Codewars 刷題

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

Codewars LV6


題目(Write Number in Expanded Form)

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.
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

影片解題:


答案:

# 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/


上一篇
Day23 - Codewars 刷題
下一篇
Day25 - Codewars 刷題
系列文
自我挑戰 Ruby 刷題 30 天31

尚未有邦友留言

立即登入留言