Leet Code 알고리즘
(Leet Code c++)Valid Perfect Square
naeunchan
2021. 8. 4. 10:37
728x90
반응형
367. Valid Perfect Square
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
Constraints:
- 1 <= num <= 2^31 - 1
이분 탐색을 통한 문제 풀이.
class Solution {
public:
bool isPerfectSquare(int num) {
int front = 1;
int back = num;
while(front <= back){
int mid = front + (back - front) / 2;
if(mid == (double)num / (double)mid){
return true;
}
else if(num / mid > mid){
front = mid + 1;
}
else{
back = mid - 1;
}
}
return false;
}
};728x90
반응형