티스토리 뷰

PS/programmers

Level1) 하샤드 수

kingsubin 2020. 9. 12. 03:13
class Solution {
    public boolean solution(int x) {
        int sum = 0;
        char[] chars = String.valueOf(x).toCharArray();
        for (char c : chars) {
            sum += c - '0';
        }

        return x % sum == 0;
    }
}

- 성공 

 

- char 타입으로 바꿔서 풀이

 

class Solution {
    public boolean solution(int x) {
        int mod = x;
        int sum = 0;
        do {
            sum += (mod % 10);
            mod /= 10;
        } while(mod % 10 > 0);

        return x % sum == 0;
    }
}

- 다른 사람 풀이

- 숫자 자체로 각 자릿수를 뽑아서 합을 구함

'PS > programmers' 카테고리의 다른 글

Level1) 두 개 뽑아서 더하기  (0) 2020.10.08
Level1) x만큼 간격이 있는 n개의 숫자  (0) 2020.09.12
Level1) 콜라츠 추측  (0) 2020.09.12
Level1) 최대공약수와 최소공배수  (0) 2020.09.12
Level1) 정수 제곱근 판별  (0) 2020.09.12