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?