Algorithm/JAVA - BOJ

BOJ/백준 - 2231 분해합 JAVA

ㅇㅇ잉 2021. 8. 12. 14:40

브루트포스 문제니까, 일단 다 탐색해야하는구나~하고 접근

가장 작은 생성자를 찾는거니까 작은 수부터 계산해준다.

 

그리고 입력 방식을 다르게 두 번 풀어봤다.

 

 

1.Scanner 이용

 

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
import java.util.*;
 
public class Main {
 
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
 
        int N = in.nextInt();
 
        int result = 0;
        for(int i=1;i<=N;i++){
            int sum=0;
            int tmp=i;
 
            while(tmp!=0){
                sum+=tmp%10;
                tmp/=10;
            }
 
            if(sum+i==N){
                result = i;
                break;
            }
        }
 
        System.out.print(result);
    }
}
cs

 

 

 

2. BufferedReader 이용


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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
 
public 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 result = 0;
        for(int i=1;i<=N;i++){
            int sum=0;
            int tmp=i;
 
            while(tmp!=0){
                sum+=tmp%10;
                tmp/=10;
            }
 
            if(sum+i==N){
                result = i;
                break;
            }
        }
 
        System.out.print(result);
    }
}
 
cs

 

 

그리고 두 개 차이

위가 BufferedReader, 아래가 Scanner