카테고리 없음

프로그래머스 Level2 - 다음 큰 숫자 C++

ㅇㅇ잉 2021. 4. 15. 01:59

입력받은 n의 수와, n보다 큰 수부터 차례로 2진수를 구했을 때 1의 갯수가 같은 것을 return시켜주면 되는 문제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <string>
#include <vector>
#include <iostream>
 
using namespace std;
 
int cnt (int num){
    
    int result = 0;
    while(num){
        if(num%2==1) result++;
        num/=2;
    }
    
    return result;
}
 
int solution(int n) {
    int answer = 0;
    int n_cnt = cnt(n);
    
    while(1){
        int tmp = cnt(++n);
        if(n_cnt == tmp) return n;
    }
    
    return answer;
}
cs

 

 

이건 비트연산으로 한 방법.

left shiht로 밀면서 : num>>=1

비트가 1인지아닌지 확인한다. : if(num & 0x01) 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <string>
#include <vector>
#include <iostream>
 
using namespace std;
 
int cnt (int num){
    
    int result = 0;
    while(num){
        if(num & 0x01) result++;
        num>>=1;
    }
    
    return result;
}
 
int solution(int n) {
    int answer = 0;
    int n_cnt = cnt(n);
    
    while(1){
        int tmp = cnt(++n);
        if(n_cnt == tmp) return n;
    }
    
    return answer;
}
cs