문제
https://www.acmicpc.net/problem/2231
2231번: 분해합
어떤 자연수 N이 있을 때, 그 자연수 N의 분해합은 N과 N을 이루는 각 자리수의 합을 의미한다. 어떤 자연수 M의 분해합이 N인 경우, M을 N의 생성자라 한다. 예를 들어, 245의 분해합은 256(=245+2+4+5)이
www.acmicpc.net
import java.util.Scanner;
public class Main2231 {
static int N; // 입력받은 정수(분해합)
static int ans = Integer.MAX_VALUE; // 생성자(최대값으로 초기화)
// 분해합, 인덱스를 인자로 받는다.
public static void constructor(int res, int idx) {
int temp = 0;
int result = 0;
if (idx > N) {
ans = 0;
return;
}
if (res == N) {
ans = idx-1;
return;
} else if (res != N){
temp = result = idx;
while (temp != 0) {
result += temp%10;
temp /= 10;
}
idx++;
constructor(result, idx);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
sc.close();
constructor(0, 1);
System.out.println(ans);
}
}
1. 우여곡절이 있긴했지만 정답.
2. constructor 메소드에서 첫번째 조건문을 맨뒤로 옮기면 stackOverFlow예외가 발생된다. 재귀방식으로 진행했기 때문에 그렇다.
3. 이전에 비슷한 문제를 풀어봐서 큰 도움이 됐다.
https://ahlight.tistory.com/26
백준 4673번
문제 https://www.acmicpc.net/problem/4673 4673번: 셀프 넘버 셀프 넘버는 1949년 인도 수학자 D.R. Kaprekar가 이름 붙였다. 양의 정수 n에 대해서 d(n)을 n과 n의 각 자리수를 더하는 함수라고 정의하자. 예를 들
ahlight.tistory.com
'백준' 카테고리의 다른 글
백준 22864번 (0) | 2022.11.15 |
---|---|
백준 19532번 (0) | 2022.11.10 |
백준 14889번 (0) | 2022.11.08 |
백준 2798번 (0) | 2022.11.05 |
백준 10819번 ☆ (0) | 2022.11.03 |