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

  • 相关阅读:
    设计模式的类型
    SQL介绍(1)
    MySQL(介绍1)
    MyBatis总结(1)
    使用SQLServer Profiler侦测死锁(转)
    SQL Server 数据库中关于死锁的分析
    Delphi内嵌汇编语言BASM精要(转帖)
    Delphi项目构成之单元文件PAS
    Delphi中Interface接口的使用方法
    Delphi项目构成之项目文件DPR
  • 原文地址:https://www.cnblogs.com/yrbbest/p/4491663.html
Copyright © 2011-2022 走看看