TypechoJoeTheme

IT技术分享

统计

[LeetCode 191] Number of 1 Bits [Java] [Runtime : 1MS]

2017-08-31
/
0 评论
/
643 阅读
/
正在检测是否收录...
08/31

1. Description

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.

2. Runtime Distribution

3. Submission Details

4. Example

Input: 9
Ouput: 2

5. Code

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

6.Test

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

    public static void main(String[] args) {
        LeetCode0191 leetcode = new LeetCode0191();
        System.out.println(leetcode.hammingWeight(15));
    }
}
BIT
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/758/(转载时请注明本文出处及文章链接)