-2

I am solving this question:

Given a positive integer num, write a function that returns True if num is a perfect square else False.

Input: num = 16

Output: true

My solution:

import math
class Solution:
    def isPerfectSquare(self, num: int) -> bool:
    
         return type(math.sqrt(16))=='int' //4.0=='int'

I know there are a lot of different solutions which are easier but I want to know how we can get this right as I can't use int to make it integer as 4.5 will also be the correct answer.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

-1

math.sqrt's default return type is float so you should check if the square root and floor of square root are equal or not to identify a perfect square...

This will work...

import math
class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        sqroot = math.sqrt(num)
        return sqroot == math.floor(sqroot)
MohammadArik
  • 71
  • 1
  • 9
  • 3
    You shouldn't be using `==` with floats. See [Is floating point math broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). (Also, using `sqrt` as a variable name isn't a good idea.) – JohanC Aug 25 '21 at 09:45
  • 1
    Better use `round(sqroot) ** 2 == num` and tell about the restriction of `num` to something around `2**26` – Wolf Aug 25 '21 at 11:38
  • @Wolf thats also doable but the current solution will is faster. It wont matter in small numbers but in time of big numbers, it will be a problem.. – MohammadArik Aug 26 '21 at 01:54