【LeetCode】Number of 1 Bits 解题报告

Number of 1 Bits

[LeetCode]

https://leetcode.com/problems/number-of-1-bits/

Total Accepted: 88721 Total Submissions: 236174 Difficulty: Easy

Question

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.

Ways

方法一

其实就是不断地右移。判断最后一位总共出现了多少次1.

刚开始没有AC的原因是java是没有无符号整数的,也就是说int的最高位是1的话会认为是负数,所以普通右移并且判断n==0会超时,判断n>0的话直接不运行。

还好java提供了不保持符号位的>>>。

>>是符号位保持不变的右移。

用左移的方法好像不用考虑这么多。

本来是想用n%2==1来判断是否最后一位是1的,效率太差,用n&1的方式可以加快最后一位计算时的速率。

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int answer=0;
        while(n!=0){
            answer+=n&1;
            n>>>=1;
        }
        return answer;   
    }
}

AC:2ms

方法二

LeetCode给出的另一种巧妙解法。

当n&(n-1)!=0时说明n中至少包含一个1.

通过不停的n=n&(n-1)的方法可以将最后的一个1消掉。

We can make the previous algorithm simpler and a little faster. Instead of checking every bit of the number, we repeatedly flip the least-significant 11-bit of the number to 00, and add 11 to the sum. As soon as the number becomes 00, we know that it does not have any more 11-bits, and we return the sum.

The key idea here is to realize that for any number nn, doing a bit-wise AND of nn and n - 1n−1 flips the least-significant 11-bit in nn to 00. Why? Consider the binary representations of nn and n - 1n−1.

public int hammingWeight(int n) {
    int sum = 0;
    while (n != 0) {
        sum++;
        n &= (n - 1);
    }
    return sum;
}

Date

2016/5/1 14:31:33

你可能感兴趣的:(LeetCode)