알고리즘/백준 알고리즘

[java] 백준 알고리즘 4673번 셀프 넘버 풀이

희랍인 조르바 2018. 5. 17. 15:34


* 풀이소스


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
31
32
33
34
35
36
37
38
39
40
public class Baekjoon4673 {
 
    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        List<String> willBeSelfNumber = new ArrayList<>();
        
        for(int i=1; i<=10000; i++) { // 1~10000까지 셀프 넘버를 담기 위한 list를 미리 만들어준다. 
            willBeSelfNumber.add(String.valueOf(i));
        }
        
        int n = 1;
        String result = null;
        
        while(n <= 10000) {
            result = String.valueOf(d(n));
            
            if(willBeSelfNumber.contains(result)) { // 연산으로 만들어진 수를 찾는다
                willBeSelfNumber.remove(result); // 연산으로 만들어진 수를 모두 빼주면 셀프 넘버만 남는다
            }
            n++;
        }
        
        for(int j=0; j<willBeSelfNumber.size(); j++) {
                bw.write(willBeSelfNumber.get(j));
                bw.newLine();
        }
        bw.flush();
    }
    
    private static int d(int constructor) { // 생성자가 될 수가 들어오면 문제의 연산대로 가공해주는 함수
        String stringN = String.valueOf(constructor);
        
        for(int i=0; i<stringN.length(); i++) {
            constructor += Character.getNumericValue(stringN.charAt(i)); // 각 자릿수와 입력된 수를 합친 수가 만들어짐
        }
        
        return constructor;
    }
}
 
cs