본문 바로가기

프로그래머스/lv1

정수 제곱근 판별

/* 정수 제곱근 판별
 * 임의의 양의 정수 n에 대해,
 * n이 어떤 양의 정수 x의 제곱인지 아닌지 판단하려 합니다.
 * n이 양의 정수 x의 제곱이라면 x+1의 제곱을 리턴하고,
 * n이 양의 정수 x의 제곱이 아니라면 -1을 리턴하는 함수를 완성하세요.
 *
 * n    return
 * 121  144     121은 양의 정수 11의 제곱이므로, (11+1)를 제곱한 144를 리턴합니다.
 * 3    -1      3은 양의 정수의 제곱이 아니므로, -1을 리턴합니다.
 */

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class programmer_1_12 {
    static long a1 = 1;
    static long a2 = 3;
    public long solution(long n) {
        long answer = 0;
        for(long i = 1; i <= n; i++){
            if(i*== n){
                answer = i + 1;
                break;
            }
            else answer = -1;
        }
        return answer == -1 ? answer : answer * answer;
        /* 다른 사람 풀이
        if (Math.pow((int)Math.sqrt(n), 2) == n) {
            return (long) Math.pow(Math.sqrt(n) + 1, 2);
        }
        return -1;
         */
    }
    public static void main(String args[]){
        programmer_1_12 t = new programmer_1_12();
        System.out.println("---------------------------------------");
        System.out.println("result = " + t.solution(a1));
        System.out.println("---------------------------------------");
        System.out.println("result2 = " + t.solution(a2));
        System.out.println("---------------------------------------");
    }
}
cs

'프로그래머스 > lv1' 카테고리의 다른 글

문자열을 정수로 바꾸기  (0) 2022.12.13
문자열 내 p와 y의 개수  (0) 2022.12.13
자연수 뒤집어 배열로 만들기  (0) 2022.12.13
자릿수 더하기  (0) 2022.12.08
평균 구하기  (0) 2022.12.08