-1

I'm working on this leetcode problem.

I am using print statements to debug my failing testcase (536870912).

When hardcoding the values directly (print(str(29.0 % 1 == 0))) I obtain the desired, correct result (True).

However, when using the num variable (num = 29.0), I do not obtain the correct result even though the logic should be the exact same (print(str(num % 1 == 0))) (False).

Any tips appreciated... I'm not really sure how to debug this one.

import math

class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        # the only case 'log' can't check is '2**0'
        # so weed that out in a check
        if (n == 1):
            return True
        
        # this is a clever application of modulus
        # I'm not sure I would've figured out
        
        num = math.log(n, 2)
        print(str(num))
        is_pow_2 = (num % 1 == 0)
        print(str(is_pow_2))
        print(str(29.0 % 1 == 0))
        
        return (num % 1 == 0)
griffin_cosgrove
  • 419
  • 8
  • 16
Jenilee Chen
  • 1
  • 1
  • 2
  • 2
    When I print num, I see `29.000000000000004`, as log2 doesn't return the exact value, you can't use that way. See https://stackoverflow.com/questions/588004/is-floating-point-math-broken – azro Jul 01 '20 at 20:09
  • 1
    `num = math.log(n, 2)` is going to give you a `float` object, which will not necessarily give you numerically exact results – juanpa.arrivillaga Jul 01 '20 at 20:09
  • 4
    Does this answer your question? [How to check if a given number is a power of two in Python?](https://stackoverflow.com/questions/57025836/how-to-check-if-a-given-number-is-a-power-of-two-in-python) – azro Jul 01 '20 at 20:10
  • 1
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – griffin_cosgrove Jul 02 '20 at 03:48

1 Answers1

0

You don't need to use math. The standard solution for power of two is through bitwise:

class Solution:
    def isPowerOfTwo(self, n):
        if n < 1:
            return False
        while not n & 1:
            n >>= 1

        return n == 1

References

  • For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
Emma
  • 27,428
  • 11
  • 44
  • 69