标签:
Write a function that takes an unsigned integer and returns the number of ’1‘ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11‘ has binary representation 00000000000000000000000000001011
, so the function should return 3.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
思路分析:这题考察位运算,比较容易想到的思路是不断进行左移位操作然后并且和1做&运算,就可以每次判定最后一位是否是1,从而得到1的个数,见注释的code,这种算法需要做32次移位操作。这题有更快的解法,那就是利用n&(n-1)可以去掉最右侧的1,例如
n 000110100
n-1 000110011
&后 000110000
最右侧的1消失。于是我们可以不断做这样的操作直到n变成0。就可以知道有多少个1。n&(n-1)还有一个应用,就是快速判断某个数是否是2的k次方,即判断某个数的二进制表示是否只包括一个1,
AC Code
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int counter = 0; /*while(n!=0){ n = n & (n-1); counter++; } return counter;*/ for(int i = 0; i<32 ; i++){ counter += n&1; n = n>> 1; } return counter; } }
int x = 1;
String bin = Integer.toBinaryString(x);
System.Out.Println(bin);
上面给出了把某个整数转化成其二进制表示的方法,代码输出0000 0001
关于位操作,还看到一个很有意思的讨论,关于右移位操作时,左边是补充0还是补充1的讨论问题
I am very confused on right shift operation on negative number, here is the code.
int n = -15;
System.out.println(Integer.toBinaryString(n));
int mask = n >> 31;
System.out.println(Integer.toBinaryString(mask));
And the result is:
11111111111111111111111111110001
11111111111111111111111111111111
Why right shifting a negative number by 31 not 1 (the sign bit)?
Answer
Because in Java there are no unsigned datatypes, there are two types of right shifts: arithmetic shift >>
and logical shift >>>
. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
Arithmetic shift >>
will keep the sign bit.
Unsigned shift >>>
will not keep the sign bit (thus filling 0
s).
(images from Wikipedia)
引用地址 http://stackoverflow.com/questions/15457893/java-right-shift-on-negative-number标签:
原文地址:http://blog.csdn.net/yangliuy/article/details/46502357