[Leet Code] Valid Perfect Square

Matthew Boyd
1 min readNov 28, 2020

--

Leetcode: https://leetcode.com/problems/valid-perfect-square/

Problem:

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:

Input: num = 16
Output: true
Input: num = 14
Output: false

Solution:

class Solution(object):
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
value = num ** 0.5
return value - int(value) == 0

Explanation:

This should be a quick and easy explanation: we get the square root value, then we basically need to check if there is a decimal point other than 0. So value will give us the square root value, then if we convert this to an int and value has any decimal points, if we minus the int, it will not equal 0, therefore it would be false, otherwise, if it is 0, it will be true!

--

--

Matthew Boyd
Matthew Boyd

Written by Matthew Boyd

Learning, and posting my findings!

No responses yet