Skip to content

Commit ace394e

Browse files
committed
풀이: 릿코드.868.Binary Gap
?: 순회를 이용해 풀이
1 parent 9a254a7 commit ace394e

3 files changed

Lines changed: 100 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# 868. Binary Gap
2+
3+
[링크](https://leetcode.com/problems/binary-gap/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+
비트를 순회하며 1이 나올 때마다 이전에 나온 1과의 거리를 계산하여 최대값을 갱신한다.
28+
29+
```cpp
30+
int binaryGap(int n) {
31+
int answer = 0;
32+
int count = 0;
33+
int before = 32;
34+
35+
while (n > 0) {
36+
if (n % 2 == 1) {
37+
answer = max(answer, count - before);
38+
before = count;
39+
}
40+
41+
n /= 2;
42+
count++;
43+
}
44+
return answer;
45+
}
46+
```
47+
48+
## 고생한 점
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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 binaryGap(int n) {
25+
int answer = 0;
26+
int count = 0;
27+
int before = 32;
28+
29+
while (n > 0) {
30+
if (n % 2 == 1) {
31+
answer = max(answer, count - before);
32+
before = count;
33+
}
34+
35+
n /= 2;
36+
count++;
37+
}
38+
return answer;
39+
}
40+
};
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
Input: n = 22
2+
Output: 2
3+
4+
===
5+
6+
Input: n = 8
7+
Output: 0
8+
9+
===
10+
11+
Input: n = 5
12+
Output: 2

0 commit comments

Comments
 (0)