Skip to content

Latest commit

 

History

History
39 lines (24 loc) · 1.12 KB

File metadata and controls

39 lines (24 loc) · 1.12 KB

🐩 LeetCode 231. Power of Two

  • Date : 2021.08.08(일)
  • Time : 25분

Problem

  • 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.

Constraints

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

Example

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



풀이

    def isPowerOfTwo(self, n: int) -> bool:

        if n == 1:
            return True
        if n % 2 == 1 or n == 0:
            return False

        return self.isPowerOfTwo(n // 2)

: 이 문제는 이 값을 2의 n제곱을 통해 만들 수 있는지를 판단하는 문제이다. 그래서 재귀호출을 이용했다. 이 때 조건은 만약 n == 1이라면 제곱을 푸는 과정이 끝난 것이므로 true를 return 하였다. 하지만 n%2 == 1이라면 2의 n제곱을 통해 만들 수 없는 숫자라는 의미기 때문에 False이고, n == 0 도 나눌 수 없기 때문에 False이다. 그리고 만약 if문에 걸리지 않았다면 더 나눠봐야 하기때문에 재귀호출을 시작하였다.