Skip to content

Commit

Permalink
Create valid-perfect-square.py
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Jun 26, 2016
1 parent c9babbf commit bafc1bf
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions Python/valid-perfect-square.py
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

0 comments on commit bafc1bf

Please sign in to comment.