프로그래머스

프로그래머스 다음 큰 숫자, c++

2024. 2. 13. 20:18

 

 

 

1. 받아온 숫자를 2진수로 변환하는 함수 구현

string nTOtwo(int n) {
	string str = "";
	while(n>0) {
    	int i = n % 2;    //나머지
    	n /= 2;           //몫
        str = to_string(i) + str; 
    }
	return str;
}

 

 

 

 

2. 2진수 안의 1의 개수를 세는 함수 구현

int count1 (string &s) {
	int ncount = 0;
	for(int i=0; i<s.length(); i++) {
    	if(s[i] == '1')
        	ncount++;
    }
    return ncount;
}

 

 

 

3. solution함수

처음 받아온 숫자 n을 2진수로 변환해 그 1의 개수를 센다.

n+1부터 순서대로 돌아가며 n과 "2진수의 1의 개수" 가 같은 경우를 출력한다.