LeetCode Number of 1 Bits

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,

n&(n-1) == 0 and n != 0 iff n == 2^k (only one bit is 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.
Arithmetic shift

Unsigned shift >>> will not keep the sign bit (thus filling 0s).
Logical shift

(images from Wikipedia)

引用地址 http://stackoverflow.com/questions/15457893/java-right-shift-on-negative-number




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值