백준/2231/brute force/분해합

유기태·2022년 5월 17일
0

백준/2231/brute force/분해합
받은 자연수보다 작은 수들 중에서 1부터 시작하여
각 자릿수별로 나누어 더해서 N고 같다면 반복문을 탈출하게 끔하였다.

풀이

1.첫번째 풀이

#include<iostream>
using namespace std;


int main(void) {
	int N;
	int temp = 0;
	int result = 0;
	int cons = 0;
	cin >> N;

	for (int i = 1; i < N; i++) {
		int sum = 0;
		cons = i;
		sum += cons;
		for (int j = 10000000; j > 0.1; j = j / 10) {
			temp = cons / j;
			if (temp == 0)
				continue;
			sum += temp;
			cons -= j * temp;
		}
		if (sum == N) {
			result = i;
			break; 
		}
	}

	cout << result << endl;
}

2. 두번째 풀이(모듈화)

#include<iostream>
using namespace std;

int N;
int result = 0;
int answer = 0;
int solve = 0;

void solution();

void func() {
	int temp = 0;
	for (int i = 1; i < N; i++) {
		result = 0;
		result += i;
		answer = i;
		for (int j = 1000000; j > 0.1; j = j / 10) {
			temp = answer / j;
			if (temp == 0) continue;
			result += temp;
			answer -= temp * j;
			temp = 0;
		}
		if (result == N) {
			solve = i;
			break;
		}
	}
	solution();
}

void solution() {
	cout << solve << '\n';
}

int main(void) {
	ios::sync_with_stdio(0);
	cin.tie(0);

	cin >> N;
	func();
}
profile
게임프로그래머 지망!

0개의 댓글