본문 바로가기
(문제풀이)

프로그래머스(java) : 제곱수 판별하기

by cogito-new 2022. 10. 10.

class Solution {
    public int solution(int n) {
        int answer = 0;
        int sqrt = (int)Math.sqrt(n);
       if(sqrt*sqrt==n) {
           answer = 1;
       }  else {
           answer = 2;
       }
        
        return answer;
    }
}

Math.sqrt 메소드 사용 (루트 계산 메소드)

Math.sqrt 메소드의 경우 double 형으로 return 되고, (int)로 강제 타입 변환되면

제곱수가 아니어도 제곱수 형태로 return 된다.

ex) 144 → 12이지만

145 → 강제 타입 변환시 12가 된다.

반응형