Contents

Determining the square number (with.Java)

   Apr 21, 2024     2 min read

This article examines the problem of “identifying square numbers.”

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to get to know myself.

Let’s look at the problem first.

problem

The integer that results when a natural number is squared is called a square number.

When an integer n is given as a parameter, complete the solution function so that it returns 1 if n is a square number, and 2 otherwise.

Restrictions

  • 1 ≤ n ≤ 1,000,000

Input/Output Example

nresult
1441
9762

My solution to the problem

class Solution {
     public int solution(int n) {
         int answer = 0;
         for(int i = 1; i <= 1000; i++){
             if(i * i == n){
                 answer = 1;
                 break;
             }else if(i * i > n){
                 answer = 2;
                 break;
             }
         }
         return answer;
     }
}

Solution explanation

int answer = 0;: Initialize the variable answer, which will store the result, to 0.

for(int i = 1; i <= 1000; i++): This is a loop statement to sequentially check numbers from 1 to 1000.

if(i * i == n): If the power of the current number i is equal to n, then n is a square number. So we set answer to 1 and exit the loop.

else if(i * i > n): If the current number i squared is greater than n, then n is not a square number. So we set answer to 2 and exit the loop.

return answer;: Returns the final result answer.

This code sequentially squares numbers from 1 to 1000 and compares them to n to determine whether n is a square number or not. The returned values are:

0: When n is not expressed as a square of numbers from 1 to 1000. 1: When n is expressed as the square of one of the numbers from 1 to 1000 2: When n is greater than the square of numbers from 1 to 1000