精華區beta Marginalman 關於我們 聯絡資訊
※ 引述《ZooseWu (動物園 公告)》之銘言: : 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 : } Python Code: class Solution: def hammingWeight(self, n: int) -> int: return bin(n).count("1") 滿簡單的 直接count()啟動 發現int不能直接count 所以轉成二進位 不過分數超爛 等等研究解答 -- ▄▄ ◣◢ ︻▂ ◤ ◥ `◥ 使 X /X | ◤"▼ \ ╱\~ |╲ / ` ︻ ︻ ▏ " " " " " "" " " " ▄▄▄▄▄ #wataten -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.165.165 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1701244894.A.D2C.html