[LeetCode] 191 - Number of 1 Bits
문제
- 링크: https://leetcode.com/problems/number-of-1-bits
- 난이도: Easy
- 태그: 비트 조작
- 결과:
Time: 0 ms (100%), Space: 8.10 MB (11.11%)
풀이
class Solution {
public:
int hammingWeight(int n) {
// 아주 간편한 풀이가 있지만... 직접 해보자.
// return __builtin_popcount(n);
int cnt = 0;
for (unsigned int i = 1 << 31; i > 0; i /= 2)
{
if ((n & i) != 0)
{
cnt++;
}
}
return cnt;
}
};
지난번 익혀두었던 __builtin_popcount로도 AC를 받았다!
댓글남기기