[Programmers] #120909 - 제곱수 판별하기 [Java][C++][Python]
[Programmers] #120909 - 제곱수 판별하기 [Java][C++][Python]
1. 아이디어
정수 $n$이 제곱수인지 판별하는 문제다. 제곱수라면 $\sqrt{n}$이 정확히 자연수라서 반올림하든 내림하든 얻은 정수 $r$이 그 값과 같으므로, $r^2 = n$인지 확인하면 된다. 제곱수가 아니면 $r^2 = n$인 정수 $r$이 없어 항상 어긋난다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
class Solution {
public int solution(int n) {
long r = Math.round(Math.sqrt(n));
return r * r == n ? 1 : 2;
}
}
Math.round가 long을 반환해서 r을 long으로 받았다.
1
2
3
4
5
6
7
#include <bits/stdc++.h>
using namespace std;
int solution(int n) {
int r = round(sqrt(n));
return r * r == n ? 1 : 2;
}
1
2
3
4
5
6
import math
def solution(n):
r = math.isqrt(n)
return 1 if r * r == n else 2
math.isqrt로 실수를 거치지 않고 정수 제곱근을 구했다.
This post is licensed under CC BY 4.0 by the author.