Problem
Count how many 1 in binary representation of a 32-bit integer.
Example
Given 32, return 1
Given 5, return 2
Given 1023, return 9
Challenge
If the integer is n bits with m bits. Can you do it in O(m) time?
Note
這道題,Olivia給我解決了兩個疑問,還剩一個。首先是要用無符號右移運算子>>>,其次是可以用一個不斷左移的二進位制1作為參照。那麼如何獲得一個用1來進行補位的左移的1呢?
第一種解法,num右移,每次對末位進行比較,直到num為0;
第二種解法,1左移,每次和num的第i位比較,直到i = 32;
第三種解法,num和num-1逐位與,去1,直到num為0。
Solution
1.
public class Solution {
public int countOnes(int num) {
int count = 0;
while (num != 0) {
count += (num & 1);
num >>>= 1;
}
return count;
}
};
2.
public class Solution {
public int countOnes(int num) {
int count = 0;
for(int i = 0 ; i < 32; i++) {
if((num & (1<<i)) != 0)
count++;
}
return count;
}
}
3.
public class Solution {
public int countOnes(int num) {
int count = 0;
while (num != 0) {
num &= num - 1;
count++;
}
return count;
}
}
// 1111 1110 1110
// 1110 1101 1100
// 1100 1011 1000
// 1000 0111 0000