传送门
nowcoder
leetcode
题目描述
输入一个整数,输出该数32位二进制表示中1的个数。其中负数用补码表示。
C++ 代码 - nowcoder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
class Solution { public: int NumberOf1(int n) { return bitset<32>(n).count(); } };
class Solution { public: int NumberOf1(int n) { int count = 0; for (int i = 0; i < 32; i ++) { if (n & (1 << i)) { count ++; } } return count; } };
class Solution { public: int NumberOf1(int n) { int count = 0; while (n != 0) { n = n & (n - 1); count ++; } return count; } };
|
C++ 代码 - leetcode
1 2 3 4 5 6 7 8 9 10 11
| class Solution { public: int hammingWeight(uint32_t n) { int count = 0; while (n) { n = n & (n - 1); count ++; } return count; } };
|