Created
May 9, 2020 15:01
-
-
Save Gowtham-369/00fb2edb967ff43625951e8aa7514d93 to your computer and use it in GitHub Desktop.
Day8 : 30 Day LeetCode May challenges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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