LeetCode 191 Number of 1 Bits

来源:互联网 发布:mac截图后文件在哪里 编辑:程序博客网 时间:2024/06/06 04:59

题目描述

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. JDK:int bitCount(int i)

效率肯定高,JDK源码+_+

    /**     * Returns the number of one-bits in the two's complement binary     * representation of the specified {@code int} value.  This function is     * sometimes referred to as the <i>population count</i>.     *     * @param i the value whose bits are to be counted     * @return the number of one-bits in the two's complement binary     *     representation of the specified {@code int} value.     * @since 1.5     */    public static int bitCount(int i) {        // HD, Figure 5-2        i = i - ((i >>> 1) & 0x55555555);        i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);        i = (i + (i >>> 4)) & 0x0f0f0f0f;        i = i + (i >>> 8);        i = i + (i >>> 16);        return i & 0x3f;    }

2. 思路

思路一☹:分别判断每一位,有n位就要判断n次。

思路二☺:有几个1就判断几次。参考如何判断一个数是2的n次方?判断i&(i-1)是不是0即可~

代码

    public static int hammingWeight(int n) {        int rt = 0;        while (n != 0) {            n = n & (n - 1);            rt++;        }        return rt;    }
1 0
原创粉丝点击