본문 바로가기

프로그래머스/lv1

하샤드 수

/* 하샤드 수
 * 양의 정수 x가 하샤드 수이려면 x의 자릿수의 합으로 x가 나누어져야 합니다.
 * 예를 들어 18의 자릿수 합은 1+8=9이고, 18은 9로 나누어 떨어지므로 18은 하샤드 수입니다.
 * 자연수 x를 입력받아 x가 하샤드 수인지 아닌지 검사하는 함수, solution을 완성해주세요.
 *
 * arr  return
 * 10   true       10의 모든 자릿수의 합은 1입니다. 10은 1로 나누어 떨어지므로 10은 하샤드 수
 * 12   true       12의 모든 자릿수의 합은 3입니다. 12는 3으로 나누어 떨어지므로 12는 하샤드 수
 * 11   false      11의 모든 자릿수의 합은 2입니다. 11은 2로 나누어 떨어지지 않으므로 11는 하샤드 수 X
 * 13   false      13의 모든 자릿수의 합은 4입니다. 13은 4로 나누어 떨어지지 않으므로 13은 하샤드 수 X
 */

 

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
public class programmer_1_16 {
    static int a1 = 10;
    static int a2 = 12;
    static int a3 = 11;
    static int a4 = 13;
    public boolean solution(int x) {
        boolean answer = true;
        int total = 0;
        String[] ar = Integer.toString(x).split("");
        for(String i : ar) total += Integer.parseInt(i);
 
        return x % total == 0 ? answer : false;
    }
    public static void main(String args[]){
        programmer_1_16 t = new programmer_1_16();
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(a1));
        System.out.println("---------------------------------------");
        System.out.println("result2 = " + t.solution(a2));
        System.out.println("---------------------------------------");
        System.out.println("result3 = " + t.solution(a3));
        System.out.println("---------------------------------------");
        System.out.println("result4 = " + t.solution(a4));
        System.out.println("---------------------------------------");
    }
}
cs