iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 27
1
自我挑戰組

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

Day27 - Codewars 刷題

倒數三天強度不升級下怎行呢
Codewars LV4
打算一氣呵成寫完,結果後面卡住 (暈
正確解法明天補上~


題目(Next bigger number with the same digits)

You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits:

12 ==> 21
513 ==> 531
2017 ==> 2071
If no bigger number can be composed using those digits, return -1:

9 ==> -1
111 ==> -1
531 ==> -1
def next_bigger(n)
  #your code here
end

Test.assert_equals(next_bigger(12),21)
Test.assert_equals(next_bigger(513),531)
Test.assert_equals(next_bigger(2017),2071)
Test.assert_equals(next_bigger(414),441)
Test.assert_equals(next_bigger(144),414)

影片解題:


答案:

# Next bigger number with the same digits
def next_bigger(n)
  n.to_s.split('').permutation(n.to_s.length).map(&:join).select{ |x| return x.to_i if x.to_i > n }
  -1
end
#非正確答案喔!!

下集待續..

本文同步發布於 小菜的 Blog https://riverye.com/


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

尚未有邦友留言

立即登入留言