이 문제는
216 = 198 + 1 + 9 + 8
216과 같은 분해합이 주어질 때 가장 작은 198과 같은 생성자를 구하는 문제이다.
일단 나의 접근은
분해합이 주어졌을 때 적어도 생성자는 x + 9 + 9 +9 = 분해합
x = 분해합 - (9+9+9)보다는 클 것이다라는 전제로 문제를 풀었다.
import java.util.*;
import java.io.*;
class Main{
public static void main(String[] args) throws IOException{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int N =n;
int length=0;
// 자릿수 구하기
while(N!=0) {
N/=10;
length++;
}
//그 자리숫만큼 9를 곱해서 빼주기
N=n-9*length;
//생성자 N
// answer = N에 대한 분해합
// 문제에 주어진 분해합 n
while(true) {
int answer =N;
int NN=N;
while(NN!=0) {
answer+= NN%10;
NN= NN/10;
}
if(n==answer)
break;
N++;
}
System.out.println(N);
}
}
이거 왜 시간초과가 나는지 알았다.
내가 while(true)를 사용했는데
문제의 조건이 없는 경우 0을 출력하라고 나와있는데
그 내용을 넣지 않아서 생성자가 없는경우 무한으로 while문을 빠져나가지 못하고 계속 도는 것이다.
따라서 위 코드의 문제는 내가 생성자가 없는 경우 루프를 빠져나가는 조건문을 추가하지 않았기 때문에 시간초과가 발생하는 것이다!!
따라서 아래와 같이 수정한다.
import java.util.*;
import java.io.*;
class Main{
public static void main(String[] args) throws IOException{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int N =n;
int length=0;
// 자릿수 구하기
while(N!=0) {
N/=10;
length++;
}
// 그 자리숫만큼 9를 곱해서 빼주기
N=n-9*length;
//생성자 N
// answer = N에 대한 분해합
// 문제에 주어진 분해합 n
while(true) {
int answer =N;
int NN=N;
while(NN!=0) {
answer+= NN%10;
NN= NN/10;
}
if(n==answer) {
System.out.println(N);
break;
}
N++;
if(N==n) {
System.out.println(0);
break;
}
}
}
}
for문을 통해서 푸는 다른 한가지의 방법
import java.util.*;
import java.io.*;
class Main{
public static void main(String[] args) throws IOException{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String str_n = br.readLine();
int index_num = str_n.toCharArray().length;
int n = Integer.parseInt(str_n);
int min_R = n- 9*index_num;
for(int i=min_R;i<n;i++) {
int sum = i;
int Number =i;
for(int j=0;j<index_num;j++) {
sum+=Number%10;
Number/=10;
}
if(sum==n) {
System.out.println(i);
break;
}
else if(i==n-1) System.out.println(0);
}
}
}