Re: [閒聊] 每日LeetCode已回收
191. Number of 1 Bits
檢查輸入進來的數字有幾個bit是1
Input: n = 00000000000000000000000000001011 Output: 3
Input: n = 00000000000000000000000010000000 Output: 1
Input: n = 11111111111111111111111111111101 Output: 31
Intuition:
用位元運算符計算尾數是不是1就好
Approach:
我本來以為這一題超簡單
結果我被TS搞了兩次
一次是我用遞迴去寫結果超過推疊上限
後來才查了才知道js不支援tail call
所以我就改用迴圈
結果還遇到另一個問題
js的number位數可以到53位
但是拿去做位元運算符會強制降成31位數的數字
所以第32位數字要另外手動處理
TS Code:
function hammingWeight (n: number): number {
let result = 0
if (n >= 2147483648) {
n = n - 2147483648
result = 1
}
while (n > 0) {
result += n & 1
n = n >> 1
}
return result
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.32.229.33 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1701227273.A.A60.html
推
11/29 11:24,
2年前
, 1F
11/29 11:24, 1F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 556 之 719 篇):