日期:2014-05-20  浏览次数:20766 次

又一个java位运算问题
给定一个正整数,能否通过位运算求出化成二进制后包含的1的个数;如果不能,能否通过整数运算而不是字符串运算来达到这一目的?
比如19,化成二进制为10011,里面有3个1,我就返回3.

------解决方案--------------------
public class Test {
public static void main(String args[]) {
System.out.println(countOne(19));
}

public static int countOne(int m) {
int count = 0;
while(m > 0) {
if(0 != (m & 1))
++count;
m = m > > > 1;
}
return count;
}
}
------解决方案--------------------
另外一个帖子里面,我写的代码,

if ((num & mask) != 0)的时候你count++就可以了


还有简单的代码
Integer.toBinaryString(num).replaceAll( "0 ", " ").length()