Leetcode # 869. Reordered Power of 2
Problem
https://leetcode.com/problems/reordered-power-of-2
Solution
- The leading digit is not zero. ⇒ 只要檢驗與 n 等長的 2k
- 1 <= n <= 109 ⇒ ∀ i = 0, 1, 2, …, 9; Counter(str(n))[str(i)] ≤ 9
- x_code :=
{type(x_code).__name__ = ‘str’, type(x).__name__ = ‘int’ | x_code[i] == str(Counter(str(x))[str(i)])}
Time Complexity: O(log(n))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)
class Solution:
def reorderedPowerOf2(self, n: int) -> bool:
str_n = str(n)
n_digits = Counter(str_n)
n_code = code = "".join([str(n_digits[str(i)]) for i in range(10)])
p = 1
while (p_len := int(log10(p)) + 1) <= len(str_n):
if p_len == len(str_n):
p_digits = Counter(str(p))
p_code = "".join([str(p_digits[str(i)]) for i in range(10)])
if p_code == n_code: return True
p *= 2
return False
Last Updated on 2025/08/13 by A1go