标签:wiki 效率 weight href class span repr function sig
Problem:
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.
Summary:
求三十二位无符号数含1的位数。
Analysis:
1. 最简单的思路为将n移位直至n为0,每移位一次判断最低位是否为1。但若有1在最高位则需移位32次,效率太低。
1 class Solution { 2 public: 3 int hammingWeight(uint32_t n) { 4 int cnt = 0; 5 while (n) { 6 cnt += n & 1; 7 n = n >> 1; 8 } 9 10 return cnt; 11 } 12 };
2. 下面这种思路能够把移位的次数降低至与含1的位数相等,大大提高了效率。
举个栗子:若n = 1010010,则:
可以看出,每进行一次n & (n - 1)操作,最低位上的1就会被消去。
1 class Solution { 2 public: 3 int hammingWeight(uint32_t n) { 4 int cnt = 0; 5 while (n) { 6 n &= (n - 1); 7 cnt++; 8 } 9 10 return cnt; 11 } 12 };
标签:wiki 效率 weight href class span repr function sig
原文地址:http://www.cnblogs.com/VickyWang/p/6032402.html