알고리즘 문제 풀이/프로그래머스
[Algorithm] 프로그래머스 - 제곱수 판별하기 (Kotlin)
참깨빵위에참깨빵_
2023. 1. 10. 18:16
728x90
반응형
어떤 자연수를 제곱했을 때 나오는 정수를 제곱수라 한다. 정수 n이 매개변수로 주어질 때 n이 제곱수면 1, 아니면 2를 리턴하는 solution()을 완성하라
Math 클래스의 sqrt()라는 메서드를 쓰면 되는 문제다. sqrt()는 아래와 같은 함수다.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.math/sqrt.html
sqrt - Kotlin Programming Language
kotlinlang.org
값 x(매개변수)의 양의 제곱근을 계산한다
이걸 써서 주먹구구식으로 푼 코드는 아래와 같다.
import kotlin.math.sqrt
class Solution {
fun solution(n: Int): Int {
var answer = 0
val sqrt = sqrt(n.toDouble())
answer = if (sqrt == sqrt.toInt().toDouble()) {
1
} else {
2
}
return answer
}
}
간단하게 줄이면 아래와 같아진다.
import kotlin.math.sqrt
class Solution {
fun solution(n: Int): Int {
val sqrt = sqrt(n.toDouble()).toLong()
return if (sqrt * sqrt == n.toLong()) 1 else 2
}
}
반응형