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
Solution:
class Solution {
public boolean isPerfectSquare(int num) {
long left = 0;
long middle = 0;
long right = num;
while (left <= right){
middle = (left + right) / 2;
long squared = middle * middle;
if (squared == num){
return true;
} else if (squared > num){
right = middle - 1;
} else {
left = middle + 1;
}
}
return false;
}
}
'Algorithms and Data Structures > Coding Practices' 카테고리의 다른 글
LeetCode 67. Add Binary (0) | 2022.06.14 |
---|---|
LeetCode 1385. Find the Distance Value Between Two Arrays (0) | 2022.06.10 |
LeetCode 852. Peak Index in a Mountain Array (0) | 2022.06.08 |
LeetCode 35. Search Insert Position (0) | 2022.06.07 |
LeetCode 374. Guess Number Higher or Lower (0) | 2022.06.04 |