문제설명
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Follow up: Do not use any built-in library function such as sqrt
.
입출력 예
Example 1:
Input: num = 16
Output: true
Example 2:
Input: num = 14
Output: false
문제 풀이
import Foundation
class Solution {
func isPerfectSquare(_ num: Int) -> Bool {
var left = 1
var right = num
while left <= right {
let middle = (left + right) / 2
let middleSquare = middle * middle
if middleSquare == num { return true }
if middleSquare < num {
left = middle + 1
} else if middleSquare > num {
right = middle - 1
}
}
return false
}
}