你必須很努力

Day21 - Codewars 刷題

2019/09/30
字數統計: 125閱讀時間: 1 min

假日來塊蛋糕
複習下二進制及 Ruby 內建好用方法

Codewars LV7


題目(Binary Addition)

1
2
3
Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.

The binary number returned should be a string.

1
2
3
4
5
6
7
8
9
def add_binary(a,b)
#your code here
end

Test.assert_equals(add_binary(1,1),"10")
Test.assert_equals(add_binary(0,1),"1")
Test.assert_equals(add_binary(1,0),"1")
Test.assert_equals(add_binary(2,2),"100")
Test.assert_equals(add_binary(51,12),"111111")


影片解題:


答案:

1
2
3
4
# Binary Addition
def add_binary(a,b)
(a + b).to_s(2)
end

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

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

發表日期:2019-09-30

更新日期:2022-12-21

CATALOG