Number of 1 Bits
题目链接:https://leetcode.com/problems/number-of-1-bits/
题目的大意是给定一个数,求形参转化成二进制后包含1的数量。
1 class Solution { 2 public: 3 int hammingWeight(uint32_t n) { 4 int count = 0; 5 while (n) { 6 count++; 7 n = n & (n - 1); 8 } 9 return count; 10 } 11 };
n = n & (n - 1); 的作用是消去二进制下的最后一个1,因此有多少个1就执行多少次,从而统计出形参的二进制包含1的数量。
浙公网安备 33010602011771号