어떤 세균은 1시간에 두배만큼 증식한다고 합니다. 처음 세균의 마리수 n과 경과한 시간 t가 매개변수로 주어질 때 t시간 후 세균의 수를 return하도록 solution 함수를 완성해주세요.
풀이 1
class Solution {
public int solution(int n, int t) {
for(int i = 1; i <=t; i++){
n *= 2;
}
return n;
}
}
풀이2
class Solution {
public int solution(int n, int t) {
return n * (int) Math.pow(2, t);
}
}
return값에 바로 n에 대한 Math.pow()함수를 통해 t만큼의 제곱수를 구할 수 있었다.
Math.pow()
주어진 수의 지수승(제곱)을 계산하는 데 사용되는 메소드
public static double pow(double base, double exponent)
ex)
public class PowExample {
public static void main(String[] args) {
double result = Math.pow(2, 3);
System.out.println("2^3 = " + result);
}
}
이 예제에서 Math.pow(2, 3)은 2의 3승을 계산하여 8.0을 반환합니다.
결과를 출력하면 "2^3 = 8.0"이 됩니다.
주의: Math.pow()의 반환 값은 항상 double 형식이므로, 정수로 표현되어야 하는 경우에는 형 변환을 고려해야 합니다.
예를 들어, int intValue = (int) Math.pow(2, 3);과 같이 사용할 수 있습니다.