• 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

  • 相关阅读:
    前端杂七杂八
    用户数据分析
    hash表
    django杂七杂八
    redis事务
    CF1457D XOR-gun
    后缀数组学习笔记
    CF1439C Greedy Shopping
    P3320 [SDOI2015]寻宝游戏
    P5327 [ZJOI2019]语言
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4491663.html
Copyright © 2020-2023  润新知