3.22 这道题,我就是用的很普通的思路
先把一个整数化成二进制,然后一位一位的对比来做的。
有点儿笨,但总归也实现了。
public class Solution {
/**
* @param num: an integer
* @return: an integer, the number of ones in num
*/
public int countOnes(int num) {
String s = Integer.toBinaryString(num);
int count = 0;
for (int i = 0; i < s.length(); i++){
if (s.charAt(i) == 49){
count++;
}
}
return count ;// write your code here
}
};
后来在网上看到这种使用位运算的计算方法,觉得好厉害。
也写了一遍,希望自己可以记住。
除了这种,网上还给了其他的很多种方法,暂时还消化不了。
public class Solution {
/**
* @param num: an integer
* @return: an integer, the number of ones in num
*/
public int countOnes(int num) {
int count = 0;
while(num > 0){
if((num & 1) == 1){
count++;
}
num >>= 1;
}
return count ;// write your code here
}
};