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