본문 바로가기
python-algorithm

leetcode 231. Power of Two

by 무적김두칠 2023. 1. 17.

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

 

Power of Two - LeetCode

Power of Two - 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 == 2x.   Example 1: Input: n = 1 Output: true Explanation: 20 = 1 Example 2: Input: n

leetcode.com

 

1
2
3
4
5
6
7
8
def Log2(x):
    return (math.log10(x) / math.log10(2)) 
 
class Solution:
    def isPowerOfTwo(self, n: int-> bool:
        if n <= 0:
            return False 
        return (math.ceil(Log2(n)) == math.floor(Log2(n)))
cs

문제 :  주어진 정수가 2의 거듭제곱인지 아닌지 구분

log를 씌우면 쉽게 풀 수 있으나 주어진 정수가 0 이하인 경우는 2의 거듭제곱이 절대 나올수가 없으므로
if 조건문으로 해결함.

Problem: Determine if a given integer is a power of 2 or not

It can be easily solved by applying log, but if the given integer is less than 0, a power of 2 can never come out.
Solved with an if conditional statement.

반응형

댓글