프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이과정
이 문제는 10진수를 2진수로 바꾼 뒤, 1의 개수만 같으면 되기 때문에 특별히 reverse를 해주지 않았다.
처음 n을 2진수로 변경했을 때 1의 개수를 cnt1에 담고,
n을 계속 1씩 더하여 2진수로 변경했을 때 1의 개수를 res에 담아서
두 값이 같다면 무한 반복문을 탈출하여 n값을 리턴하는 식으로 구현했다.
#include <string>
#include <vector>
using namespace std;
string binary(int n){
string str = "";
while(n != 0){
str += to_string(n % 2);
n /= 2;
}
return str;
}
int solution(int n) {
int answer = 0;
int cnt1 = 0;
string str = binary(n);
for(int i = 0; i < str.size(); i++){
if(str[i] == '1') cnt1++;
}
while(1){
n++;
str = binary(n);
int res = 0;
for(int i = 0; i < str.size(); i++){
if(str[i] == '1') res++;
}
if(cnt1 == res) break;
}
answer = n;
return answer;
}
'🍞 Problem Solving > Programmers' 카테고리의 다른 글
[프로그래머스][Level2] 멀리 뛰기 c++ (0) | 2022.10.20 |
---|---|
[프로그래머스][Level2] 더 맵게 c++ (0) | 2022.10.20 |
[프로그래머스][Level2] 게임 맵 최단거리 c++ (0) | 2022.10.20 |
[프로그래머스][Level2] 124 나라의 숫자 c++ (0) | 2022.10.20 |
[프로그래머스][Level2] 2개 이하로 다른 비트 c++ (0) | 2022.10.20 |