zoukankan      html  css  js  c++  java
  • 191. 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.

    链接:  http://leetcode.com/problems/number-of-1-bits/

    题解:

    跟上题一样,应该有些很厉害的解法。自己只做了最naive的一种。

    Time Complexity - O(1), Space Complexity - O(1)

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count = 0;
            
            for(int i = 0; i < 32; i++) 
                if(((n >> i) & 1) == 1)
                    count++;
            
            return count;
        }
    }

    Brian Kernighan的方法

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count = 0;
            
            for (count = 0; n != 0; count++) {
                n &= n - 1;     // clear the least significant bit set
            }
            
            return count;
        }
    }

    二刷:

    Java:

    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count = 0;
            for (int i = 0; i < 32; i++) {
                if (((n >> i) & 1) == 1) {
                    count++;
                }
            }
            return count;
        }
    }
    public class Solution {
        // you need to treat n as an unsigned value
        public int hammingWeight(int n) {
            int count = 0;
            while (n != 0) {
                n &= n - 1;
                count++;
            }
            return count;
        }
    }

    三刷:

    使用一个while 循环,每次把n的最低的非0位清零。这样比计算全32位计算的位数少,但也多了每次按位与&操作的比较。

    Java:

    Time Complexity - O(1), Space Complexity - O(1)

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

    Reference:

    http://www.hackersdelight.org/hdcodetxt/pop.c.txt

    https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive

  • 相关阅读:
    [HEOI2015]兔子与樱花
    [HNOI2015]亚瑟王
    [JSOI2011]分特产
    某考试 T3 sine
    [JSOI2015]最小表示
    51NOD 1258 序列求和 V4
    Codeforces 622F The Sum of the k-th Powers
    Loj #6261. 一个人的高三楼
    [HAOI????] 硬币购物
    bzoj4318 OSU!
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4491663.html
Copyright © 2011-2022 走看看