Contents

Bacterial growth (with.Java)

   Apr 22, 2024     1 min read

This article looks into the problem of “bacterial proliferation (with.Java)”.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Let’s look at the problem first.

problem

It is said that some bacteria multiply twice in one hour.

When the initial number of bacteria n and the elapsed time t are given as parameters, complete the solution function so that it returns the number of bacteria after t time.

Restrictions

  • 1 ≤ n ≤ 10
  • 1 ≤ t ≤ 15

Input/Output Example

ntresult
2102048
715229376

My solution to the problem

class Solution {
     public int solution(int n, int t) {
         int answer = n;
         for(int i = 0; i < t; i++){
             answer *= 2;
         }
         return answer;
     }
}

Solution explanation

int answer = n;: Initializes the answer variable to n.

for(int i = 0; i < t; i++): Executes a loop that repeats from 0 to t-1.

Multiply the answer by 2.

return answer;: Finally returns the answer value.

This code has a function that repeats n t times and returns the value multiplied by 2.

For example, if n is 2 and t is 3, repeat 2 3 times and return 8.