문제
어떤 자연수 N이 있을 때, 그 자연수 N의 분해합은 N과 N을 이루는 각 자리수의 합을 의미한다. 어떤 자연수 M의 분해합이 N인 경우, M을 N의 생성자라 한다. 예를 들어, 245의 분해합은 256(=245+2+4+5)이 된다. 따라서 245는 256의 생성자가 된다. 물론, 어떤 자연수의 경우에는 생성자가 없을 수도 있다. 반대로, 생성자가 여러 개인 자연수도 있을 수 있다.
자연수 N이 주어졌을 때, N의 가장 작은 생성자를 구해내는 프로그램을 작성하시오.
입력
첫째 줄에 자연수 N(1 ≤ N ≤ 1,000,000)이 주어진다.
출력
첫째 줄에 답을 출력한다. 생성자가 없는 경우에는 0을 출력한다.
예제 입력 | 예제 출력 |
216 | 198 |
[ JAVA ]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class baekjoon_2231 { | |
static int N,len; | |
static int min = 1000000; | |
static String [] strArr; | |
public static void main(String[] args) { | |
// TODO Auto-generated method stub | |
Scanner scan = new Scanner(System.in); | |
N = scan.nextInt(); | |
len = Integer.toString(N).split("").length; | |
strArr = new String[len]; | |
solution(0,0); | |
if(min == 1000000) { | |
min = 0; | |
} | |
System.out.println(min); | |
} | |
public static void solution(int count, int sum) { | |
if(sum == N && count == len) { | |
String str = ""; | |
for(String s : strArr) { | |
str+=s; | |
} | |
int num = Integer.parseInt(str); | |
if(min > num) { | |
min = num; | |
} | |
}else if(count < len) { | |
for(int i=0; i<10; i++) { | |
strArr[count] = Integer.toString(i); | |
solution(count+1, sum+i+(int)(i*Math.pow(10, len-count-1))); | |
} | |
} | |
} | |
} |

'알고리즘 > 브루트 포스' 카테고리의 다른 글
[ 백준 1436 ] 영화감독 숌 (0) | 2021.03.31 |
---|---|
[ 백준 7568 ] 덩치 (0) | 2021.03.29 |
[ 백준 2798 ] 블랙잭 (0) | 2021.03.24 |
댓글