本文主要是介绍判断二进制数中1的个数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
public class TestYihuo {
/**
* 判断二进制数中1的个数
* @param args
*/
public static void main(String[] args) {
/*int a = 0xaf;
int b = 0xb1;
System.out.println(a^b);
System.out.println(~(a^b));*/
System.out.println(count(0xac));
System.out.println(count1(0xac));
System.out.println(count2(0xac));
}
public static int count(int v)
{
int num = 0;
while(v != 0)
{
if(v % 2 == 1)
num++;
v = v/2;
}
return num;
}
public static int count1(int v)
{
int num = 0;
while(v != 0)
{
num += v&0x01;
v >>= 1;
}
return num;
}
public static int count2(int v)
{
int num = 0;
while(v != 0)
{
v &= v-1;
num++;
}
return num;
}
}
这篇关于判断二进制数中1的个数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!