스터디/알고리즘

[medium] 869. Reordered Power of 2

졔부작 2022. 8. 26. 22:59
728x90
반응형

문제

https://leetcode.com/problems/reordered-power-of-2/

 

Reordered Power of 2 - 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


풀이방법

문제는 간단한데 풀이방법이 딱 떠오르지 않아서 다른 사람들의 풀이를 참고했다.

n을 나누거나 하는 방식으로 접근하는게 아니라 n의 범위가 1이상 10^9 이하에 초점을 맞춰야 했다.

주어진 n의 범위에 해당하는 2의 제곱수는 2^0, 2^1, ..., 2^31 이므로 이것들이 어떤 숫자들로 구성되어있는지를 저장해두고,

n의 숫자 구성이 이와 일치하는게 있는지 체크하면 된다.


코드

class Solution:
    def reorderedPowerOf2(self, n: int) -> bool:
        num_dict = {}
        num = 1
        num_dict[0] = Counter(str(num))
        for i in range(1,31):
            num *= 2
            num_dict[i] = Counter(str(num))
            
        n_dict = Counter(str(n))
        if n_dict in num_dict.values():
            return True
        else:
            return False
728x90
반응형