Day5 AcWing 85. 不用加减乘除做加法
Day5 LeetCode 191. 位1的个数
思路
- 位运算
代码
85. 不用加减乘除做加法
1 2 3 4 5 6 7 8 9 10 11
| class Solution { public: int add(int num1, int num2){ while (num2) { int sum = num1 ^ num2; int carry = (num1 & num2) << 1; num1 = sum, num2 = carry; } return num1; } };
|
191. 位1的个数
1 2 3 4 5 6 7 8 9 10 11 12
| class Solution { public: int hammingWeight(uint32_t n) { int ans=0; while(n) { ans+=n&1; n=n>>1; } return ans; } };
|