Skip to content

Latest commit

 

History

History
55 lines (43 loc) · 949 Bytes

231-power-of-two.md

File metadata and controls

55 lines (43 loc) · 949 Bytes

Power of Two

URL: https://leetcode.com/problems/power-of-two/description/

Description:

Given an integer n, return true if it is a power of two. Otherwise, return false. An integer n is a power of two, if there exists an integer x such that n == 2^x.

Example 1:

Input: n = 1
Output: true
Explanation: 2^0 = 1

Example 2:

Input: n = 16
Output: true
Explanation: 2^4 = 16

Example 3:

Input: n = 3
Output: false

Constraints:

-2^31 <= n <= 2^31 - 1

Follow up: Could you solve it without loops/recursion?

Solution Code:

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if (n==1):
            return True

        n_bin = bin(n)
        n_bin = n_bin[2:]

        if (n_bin[0]!= '1'):
            return False

        elif (n_bin.count('1')>1):
            return False

        return True