File tree Expand file tree Collapse file tree
LeetCode/easy/1009. Complement of Base 10 Integer Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # 1009. Complement of Base 10 Integer
2+
3+ [ 링크] ( https://leetcode.com/problems/complement-of-base-10-integer/description/ )
4+
5+ | 난이도 |
6+ | :----: |
7+ | Easy |
8+
9+ ## 설계
10+
11+ ### 시간 복잡도
12+
13+ 입력받은 수를 N이라 하자.
14+
15+ 각 자리수별로 순회하며 수를 완성할 경우 O(log_2(N))의 시간 복잡도를 사용한다.
16+
17+ ### 공간 복잡도
18+
19+ 순회에 O(1)의 공간 복잡도를 사용한다.
20+
21+ ### 비트 순회
22+
23+ | 내 코드 (ms) | 시간 복잡도 | 공간 복잡도 |
24+ | :----------: | :---------: | :---------: |
25+ | 0 | O(log_2(N)) | O(1) |
26+
27+ 각 자리수를 순회하며 현재 자리 비트가 0인 경우 answer에 해당 비트를 더해준다.
28+
29+ 이 때 현재 비트가 N 이상인 경우는 순회하지 않는다.
30+
31+ ``` cpp
32+ int bitwiseComplement (int n) {
33+ int answer = 0;
34+ if (n == 0) return 1;
35+ for (int i = 1; i < n; i <<= 1) {
36+ if ((n & i) == 0) {
37+ answer += i;
38+ }
39+ }
40+ return answer;
41+ }
42+ ```
43+
44+ ## 고생한 점
Original file line number Diff line number Diff line change 1+ #include < algorithm>
2+ #include < climits>
3+ #include < cmath>
4+ #include < cstring>
5+ #include < functional>
6+ #include < iostream>
7+ #include < map>
8+ #include < numeric>
9+ #include < queue>
10+ #include < set>
11+ #include < stack>
12+ #include < string>
13+ #include < unordered_map>
14+ #include < unordered_set>
15+ #include < vector>
16+
17+ using namespace std ;
18+
19+ // one pass
20+ // time : O(log_2(N))
21+ // space : O(1)
22+ class Solution {
23+ public:
24+ int bitwiseComplement (int n) {
25+ int answer = 0 ;
26+ if (n == 0 ) return 1 ;
27+ for (int i = 1 ; i < n; i <<= 1 ) {
28+ if ((n & i) == 0 ) {
29+ answer += i;
30+ }
31+ }
32+ return answer;
33+ }
34+ };
Original file line number Diff line number Diff line change 1+ Input: n = 5
2+ Output: 2
3+
4+ ===
5+
6+ Input: n = 7
7+ Output: 0
8+
9+ ===
10+
11+ Input: n = 10
12+ Output: 5
You can’t perform that action at this time.
0 commit comments