您的位置 首页 java

「LeetCode」位1的个数Java题解

# 题目

编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

示例 1:

输入:00000000000000000000000000001011

输出:3

解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 ‘1’。

来源:力扣(LeetCode)

链接:

# 代码

 
public class DayCode {
    public static void main(String[] args) {
        int n = 1;
        int ans = new DayCode().hammingWeight(n);
        System.out.println("ans is " + ans);
        
        int result  = Integer.bitCount(n);
        System.out.println("result is " + result);
    }
    /**
     * 题目链接: 
     * 时间复杂度 O(n)
     * 空间复杂度 O(1)
     * @param n
     * @return
     */    public int hammingWeight(int n) {
        int count = 0;
        while (n != 0) {
            n &= (n - 1);
            count++;
        }
        return count;
    }
}
  

Java 8 中 bitCount 的实现。

 
    /**
     * 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;
    }  

# 总结

* 今天这个题目是之前做过的一个题目,复习了一下,可以快速AC。

* 上文还贴了 Java 中 bitCount 的实现。可见,我们在生产环境中,工程实践的代码还是比较复杂的。

* 这个题目是二进制的应用,二进制可以高效地进行计算。 n = n & (n – 1) 把最低位的1变成0。

* 坚持每日一题,加油!

文章来源:智云一二三科技

文章标题:「LeetCode」位1的个数Java题解

文章地址:https://www.zhihuclub.com/182627.shtml

关于作者: 智云科技

热门文章

网站地图