Publish:

태그: ,

카테고리:

https://school.programmers.co.kr/learn/courses/30/lessons/12911
난이도 ⭐⭐

문제

다음 큰 숫자
다음 큰 숫자


나의 풀이

일단 입력 받은 숫자의 이진수를 구하고 그 이진수의 1의 갯수를 binaryCount 변수에 저장한다.
이후 반복문을 돌면서 입력 받은 숫자를 1씩 증가시켜주고,
1씩 증가시킨 숫자도 이진수로 변환하여 1의 갯수를 구한 다음 nextCount 변수에 저장한다.
binaryCountnextCount 의 값을 비교하여 같다면 반복문을 종료하고 숫자를 반환한다.

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
29
30
31
32
33
34
35
36
37
38
39
40
#include <string>
#include <vector>

using namespace std;

int ChangeBinary(int number)
{
	int count = 0;

	while (number != 0)
	{
		if (number % 2 == 1)
		{
			count++;
		}

		number /= 2;
	}

	return count;
}

int solution(int n)
{
	int binaryCount = ChangeBinary(n);

	while (true)
	{
		n++;

		int nextCount = ChangeBinary(n);

		if (binaryCount == nextCount)
		{
			break;
		}
	}

	return n;
}

이슈 및 공부한 것을 기록해두는 개인 블로그 입니다. 댓글, 피드백 환영합니다 🙂

Update:

댓글남기기