Skip to content

Instantly share code, notes, and snippets.

@Gowtham-369
Created May 9, 2020 15:01
Show Gist options
  • Save Gowtham-369/00fb2edb967ff43625951e8aa7514d93 to your computer and use it in GitHub Desktop.
Save Gowtham-369/00fb2edb967ff43625951e8aa7514d93 to your computer and use it in GitHub Desktop.
Day8 : 30 Day LeetCode May challenges
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Output: true
Example 2:
Input: 14
Output: false
class Solution {
public:
bool isPerfectSquare(int num) {
/*int n = sqrt(num);
for(int i=1; i<=n; i++){
if(i*i == num)
return true;
}
return false;
*/
/*
int i = 1;
while (num > 0) {
num -= i;
i += 2;
}
return num == 0;
*/
long low = 1, high = num;
while (low <= high) {
long mid = (low + high)>>1;//(low+high)/2
if (mid * mid == num) {
return true;
} else if (mid * mid < num) {
low = (int) mid + 1;
} else {
high = (int) mid - 1;
}
}
return false;
}
};
/*
int i = 1;
while (num > 0) {
num -= i;
i += 2;
}
return num == 0;
The time complexity is O(sqrt(n)), a more efficient one using binary search whose time complexity is O(log(n)):
int low = 1, high = num;
while (low <= high) {
long mid = (low + high) >>> 1;
if (mid * mid == num) {
return true;
} else if (mid * mid < num) {
low = (int) mid + 1;
} else {
high = (int) mid - 1;
}
}
return false;
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment