알고리즘

[LeetCode] Power of Two

유병각 2022. 5. 3. 00:20

방법_#1

단순 반복문으로 푸는 방법

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        cnt = 0
        if (n < 1):
            return False
        while (n != 1):
            m = n % 2
            if (m == 0):
                n /= 2
            else:
                break ;

        if (n == 1):
            return True
        else:
            return False

방법_#2

비트연산으로 계산하는 방법

2^0 = 1
2^1 = 10 ( 2^1 - 1 = 01)
2^2 = 100 ( 2^2 - 1 = 011)
2^3 = 1000 ( 2^3 - 1 = 0111)
2^4 = 10000 ( 2^4 - 1 = 01111)

이 특징을 활용해서 2 ^ n 과 (2 ^ n) - 1 을 비트연산하면 값이 0이 된다.

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if (n < 1):
            return False
        if (not n & (n - 1)):
            return True
        else:
            return False