Search code examples
python-3.xint

LeetCode 69 - Why int(2.0) equals 1?


My code is as following:

import math
class Solution(object):
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x == 0: return 0

        res = pow(math.e, 0.5 * math.log(x))
        print(res)

        return int(res)

This is based on the idea that image

When the test case is 4, it's expected to output 2 but it gives 1 back.

I check the value of res which is 2.0.

So what's the problem here?


Solution

  • if you print(repr(res)) you will see that res = 1.9999999999999998 the int of that is indeed 1.

    you could return ruound(res) (there is the doc of round) if that suits your use-case.

    if your are interested in integer square roots only this wikipedia article may be interesting for you.