forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
# Time: O(logn) | ||
# Space: O(1) | ||
|
||
# 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 | ||
# Returns: True | ||
# Example 2: | ||
# | ||
# Input: 14 | ||
# Returns: False | ||
|
||
class Solution(object): | ||
def isPerfectSquare(self, num): | ||
""" | ||
:type num: int | ||
:rtype: bool | ||
""" | ||
left, right = 1, num | ||
while left <= right: | ||
mid = left + (right - left) / 2 | ||
if mid >= num / mid: | ||
right = mid - 1 | ||
else: | ||
left = mid + 1 | ||
return left == num / left and num % left == 0 |