標籤:open 題意 面試官 取反 ges indicator sed image function
leetcode 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.
解法:
1.普通解法:利用1的移位相與
1 public class Solution { 2 // you need to treat n as an unsigned value 3 public int hammingWeight(int n) { 4 int flag = 1; 5 int count = 0; 6 while (flag != 0) { 7 if ((n & flag) != 0) { 8 count++; 9 }10 flag = flag << 1;11 }12 return count;13 }14 }View Code
2.能給面試官打來驚喜的解法,p80 利用減1的性質:減1其實是把最右邊的一個1之後的位取反,再與原數字相與就只剩下了前面的位。
1 public class Solution { 2 // you need to treat n as an unsigned value 3 public int hammingWeight(int n) { 4 int count = 0; 5 while (n != 0) { 6 count++; 7 n = n & (n - 1); 8 } 9 return count;10 }11 }View Code
劍指offer-java