1217. [S/W 문제해결 기본] 4일차 - 거듭 제곱
두 수가 주어졌을 때 재귀호출을 이용하여 거듭제곱 값을 구하라
재귀함수를 구현한다 ~~
import java.util.Scanner;
import java.io.FileInputStream;
class Solution
{
public static void main(String args[]) throws Exception
{
Scanner sc = new Scanner(System.in);
int T = 10;
for(int test_case = 1; test_case <= T; test_case++)
{
int t = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
System.out.printf("#%d %d\n", test_case, abs(a,b,0));
}
}
public static int abs(int a, int b, int cnt) {
if (cnt >= b) return 1;
else return a*abs(a,b,cnt+1);
}
}
abs메소드에서 재귀호출할 때
return a*abs(a,b,cnt++);
로 하니까 오버플로우가 발생했다. 후위 증가연산자를 사용했기 때문에 abs(a,b,cnt++)
함수가 호출되고 난 다음 cnt값이 올라가서 if (cnt>=b)
에서 빠져나올 수 없었기 때문이다. cnt+1
이나 ++cnt
로 하면 잘 작동한다!