Description

Starting with a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is not zero.

Return true if and only if we can do this in a way such that the resulting number is a power of 2.

Example 1:

Input: 1
Output: true

Example 2:

Input: 10
Output: false

Example 3:

Input: 16
Output: true

Example 4:

Input: 24
Output: false

Example 5:

Input: 46
Output: true

Note:

  1. 1 <= N <= 10^9

分析

题目的意思是:给定一个数N,可以重新排列数字的顺序,问是否能够构成2的指数次方。这道题我用一个字典d来存储N包含的数字,然后遍历2的指数次方t,用字典d1保存t中包含的数字的次数,然后进行判断就行了,首先长度要相等,然后字符要一样,字符的次数要一样,满足这三点才符合要求。

代码

class Solution:
def reorderedPowerOf2(self, N: int) -> bool:
d=collections.defaultdict(int)
s=str(N)
for ch in s:
d[ch]+=1
for i in range(32):
t=2**i
d1=collections.defaultdict(int)
for ch in str(t):
d1[ch]+=1
if(ch not in d):
break
if(len(d)!=len(d1)):
continue
flag=True
for k,v in d.items():
if(k in d1 and d1[k]!=v or (k not in d1)):
flag=False
break
# print(d1)
if(flag):
return True
return False

参考文献

​solution​