191. Number of 1 Bits - Easy
前往題目
想法
- 直覺想法是轉成string然後一個一個看,但這樣肯定是暴力解🤣
思路
&
AND操作,或是%
MOD操作,就可以判斷最後一位是不是1
- 判斷完後右移,直到
n
為0
這題真的簡單,但是需要Bit manipulation
的概念
Code
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
// Until n == 0
while (n != 0) {
// Or n % 2 to check the last bit
res += n & 1;
// Unsigned right shift all the bits
n = n >>> 1;
}
return res;
}
}
2024/05/02
- 想到用
And 1
,沒想到右移…
191. Number of 1 Bits - Easy
https://f88083.github.io/2023/12/27/191-Number-of-1-Bits-Easy/