Algorithm

[ 프로그래머스 ] 하샤드 수

emovie 2021. 9. 4. 02:21
class Solution {
    static int total = 0;
    
    public static void repeat(int x) {
		int quotient = x / 10;
		int remainder = x % 10;
		
		if(quotient == 0) total += remainder;
		else {
			total += remainder;
			repeat(quotient);
		}
		return;
	}
    
    public boolean solution(int x) {
        boolean answer = true;
        
        repeat(x);
        answer = (x%total==0 ? true : false);
        
        return answer;
    }
}

📝 해결

문제를 보고 재귀함수가 가장 먼저 떠올라 재귀함수를 사용해 해결되도록 구현했다.
함수가 종료되는 구간은 몫이 0일 경우 1의 자리라는 의미이므로 repeat 메서드를 호출하지 않는다.

 

📍 문제

https://programmers.co.kr/learn/courses/30/lessons/12947