Kata Practice - Binary Addition (JavaScript)

Kata Practice - Binary Addition (JavaScript)

這個系列會把自己練習過的 Kata 題目記錄下來,希望除了記錄的性質以外也能夠觀察自己撰寫程式邏輯的進化過程。如果有幸看到這邊的話也可以參考一下,再到 Codewars 的網站註冊一個帳號試著玩看看,自己蠻喜歡整個網站的得分和排行榜設定,會讓人越寫越有成就感喔!

題目

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.

Examples
1
2
1, 1 --> "10" (1 + 1 = 2 in decimal or 10 in binary)
5, 9 --> "1110" (5 + 9 = 14 in decimal or 1110 in binary)

自己的解法

1
2
3
4
5
6
7
8
9
const addBinary = (a,b) => {
const total = a+b
const num = ''
for(let i =1;i < total; i*2 ){
if(total % i === 1){
return num + 0
}
}
}

解題脈絡

這次沒有靠自己解完題目,是直接去看 discussion 的討論。

其他人的解法

1
2
3
function addBinary(a,b){
return (a+b).toString(2)
}

選擇記錄這個解法的原因

結果 JavaScript 本來就有提供計算 binary 值的功能了!但我不曉得 toString 除了把型別轉換成字串外還有這個功能,又學到新東西。

觀念釐清

其實有看到其他人寫出 binary 算法的解答,但我覺得以我目前的狀況來說先了解有方法可以使用的功能就好,之後有遇到的話再來試著寫一次看看吧!

那我們就下次見ʘ‿ʘ

評論