[LeetCode] 191번 - Number of 1 Bits [Java][C++]
[LeetCode] 191번 - Number of 1 Bits [Java][C++]
1. 아이디어
주어진 n을 이진수로 나타냈을 때 1인 비트 개수를 그대로 세면 되는 문제다. 언어 내장 함수를 활용하면 간단하게 해결할 수 있다.
2. 복잡도
| 시간복잡도 | 공간복잡도 |
|---|---|
| $O(1)$ | $O(1)$ |
3. 코드
풀이 [Java][C++]
Integer.bitCount 메서드를 활용하면 간단하게 해결할 수 있다.
1
2
3
4
5
class Solution {
public int hammingWeight(int n) {
return Integer.bitCount(n);
}
}
__builtin_popcount 함수를 활용하면 간단하게 해결할 수 있다.
1
2
3
4
5
6
7
8
9
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int hammingWeight(int n) {
return __builtin_popcount(n);
}
};
This post is licensed under CC BY 4.0 by the author.