본문 바로가기
CodingTest/Programmers

[프로그래머스] Lv.0 세균 증식

by yoondoo 2022. 11. 28.
728x90
class Solution {
    public int solution(int n, int t) {
        int answer = n;
        
        for(int i=1; i<=t; i++){
            answer *= 2;
        }
        
        return answer;
    }
}

1시간마다 2배씩 증가하므로

t시간 동안 증식된 세균수에 *2씩 해주면 된다.

answer = answer * 2;

 

비트 쉬프트 연산자 <<를 이용해서 문제를 풀 수도 있다.

2진수 특성상 왼쪽으로 한 칸씩 비트열이 이동할 때마다 2의 배수의 곱으로

오른쪽으로 이동할 시 2의 나눗샘으로 계산된다고 생각할 수 있다.

class Solution {
    public int solution(int n, int t) {
        int answer = 0;

        answer = n << t;

        return answer;
    }
}
반응형

댓글