recursion

recursion

์žฌ๊ท€๋ฅผ ์ด์šฉํ•œ ํ•œ์ž๋ฆฟ์ˆ˜ ๋งŒ๋“ค๊ธฐ

// input ์ž์—ฐ์ˆ˜ n์ด ์ฃผ์–ด์กŒ์„ ๋•Œ
// ex1) 10 ์ผ ๊ฒฝ์šฐ 1 + 0 => 1
// ex2) 456789 ์ผ ๊ฒฝ์šฐ 4 + 5 + 6 + 7 + 8 + 9 => 39
//                     39 = > 3 + 9 = > 12 
//                     12 = > 1 + 2 => 3
public class recursion {
    public static int compute(int source) {
        if (source < 10) {
            return source;
        }

        String sourceStr = Integer.toString(source);

        int sum = 0;
        for (int i = 0 ; i < sourceStr.length(); i ++) {
            char ch = sourceStr.charAt(i);
            int num = (int) ch - 48; // ์•„์Šคํ‚ค ์ฝ”๋“œ
            sum +=num;
        }
        return compute(sum); // ์žฌ๊ท€ ํ˜ธ์ถœ 
    }

    public static void main(String[] args) {
        int num = compute(456789);
        System.out.println(num); // 3
    }
}

Last updated

Was this helpful?