소프트웨어에 대한 모든 것

LeetCode 풀기 - 231. Power of Two 본문

알고리즘/LeetCode

LeetCode 풀기 - 231. Power of Two

앤테바 2021. 11. 2. 07:05
반응형

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

 

Power of Two - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1)

  • 2의 승수는 A & (A-1) = 0을 만족
    • 예시) 16 -> 10000, 16-1 -> 01111, 16 & 15 -> 10000 & 01111 = 0
class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if n == 0:
            return False 
        return (n & (n - 1)) == 0

솔루션2)

  • 왼쪽 shift 연산자를 활용
class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        m = 1
        while m < n:
            m <<= 1
        return m == n

솔루션3)

  • 오른쪽 shift 연산자를 활용
class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        count = 0
        while n > 0:
            count += n & 1
            if count > 1:
                return False
            n >>= 1
        return count == 1
반응형
Comments