/**
*题目:请实现一个函数,输入一个整数,输出该数二进制表示中1的个数。例如把9表示成二进制是1001,有2位是1。因此如果输入9,该函数输出2。
*时间:2015年8月28日09:51:19
*文件:NumberOf1.java
*作者:cutter_point
*/
package bishi.Offer50.y2015.m08.d28;
import org.junit.Test;
public class NumberOf1
{
public static int NumberOf1(int n)
{
if(n < 0)
n = -n;
else if( n == 0 )
return 0;
int count = 0;
while(n > 0)
{
//我们用位运算,一般使用到二进制的,我们使用位运算
if((n & 1) == 0x1)
{
++count;
}//if
n = n >> 1;
}//while
return count;
}
//剑指Offer给的标准答案,java中的Int类型的16进制,我不懂
/**
* 百度之后发现java中二进制存放的是补码,那么我们每次算的时候不可能先算补码,然后再算,笔试的时候,谁TM给时间啊!!!!
* 所以java建议用上面的
* @param n
* @return
*/
public static int NumberOf12(int n)
{
int count = 0;
while(n != 0)
{
++count;
n = (n - 1) & n; //这里java有一个小问题,Java中-1>>1还是-1,-1>>10还是-1,我不知道为什么,所以还是用上面的解法
}//while
return count;
}
public static void test(int n, int tag)
{
if(tag == 1)
System.out.println(NumberOf1(n));
else
System.out.println(NumberOf12(n));
}
@Test
public void test1()
{
int n = 1;
int n2 = 0x7FFFFFFF;
int n3 = 0x80000000;
int n4 = 0xFFFFFFFF;
int n5 = 0;
int n6 = -1;
test(n, 1);test(n2, 1);test(n3, 1);test(n4, 1);test(n5, 1);test(n6, 1);
}
@Test
public void test2()
{
int n = 1;
int n2 = 0x7FFFFFFF;
int n3 = 0x80000000;
int n4 = 0xFFFFFFFF;
int n5 = 0;
int n6 = -1;
test(n, 2);test(n2, 2);test(n3, 2);test(n4, 2);test(n5, 2);
test(n6, 2);
}
public static void main(String[] args)
{
int n = -1;
System.out.println(0x80000001&0x80000010);//(-1&-2)的结果是:-2147483648,我也是醉了
System.out.println(0x80000000); //这个TM不是0么,-2147483648
System.out.println(0x80000001); //这个TM不是-1么,-2147483647
System.out.println(0x80000010); //这个TM不是-2么,-2147483632
System.out.println(0x00000000 - 1); //这个TM,-1
//-1的补码,也就是,符号位还是1
System.out.println(0xffffffff); //这个才是-1
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/cutter_point/article/details/48048779