你必須很努力

Day20 - Codewars 刷題

2019/09/29
字數統計: 160閱讀時間: 1 min

2/3 過去了,發了 20 篇廢文
再 10 天就結束了,同時也是最忙的階段
一起把鐵人賽完賽吧!!

Codewars LV8


題目(Fake Binary)

1
Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'. Return the resulting string.

1
2
3
4
5
6
7
8
9
10
11
def fake_bin(s)
# Insert you code here...
end

describe "Basic test" do
it "should test for something" do
Test.assert_equals(fake_bin('45385593107843568'), '01011110001100111');
Test.assert_equals(fake_bin('509321967506747'), '101000111101101');
Test.assert_equals(fake_bin('366058562030849490134388085'), '011011110000101010000011011');
end
end


影片解題:


答案:

1
2
3
4
5
6
7
8
9
10
11
# Fake Binary
def fake_bin(s)
# 方法1
s.tr('123456789', '000011111')

# 方法2
s.chars.map{ |i| i.to_i < 5 ? 0 : 1}.join

# 方法3
s.gsub(/[1234]/, '0').gsub(/[56789]/, '1')
end

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

原文連結:https://riverye.com/2019/09/29/Day20-Codewars-刷題/

發表日期:2019-09-29

更新日期:2022-12-21

CATALOG