File tree Expand file tree Collapse file tree
LeetCode/easy/868. Binary Gap Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ ## 고생한 점
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 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+ };
Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments