# 869. 重新排序得到 2 的幂

1 <= N <= 10^9

1 <= N <= 10^9,枚举1<<0~1<<29,比较排序后的结果

py

class Solution:
def reorderedPowerOf2(self, n: int) -> bool:
cmp=sorted([int(m) for m in str(n)])
for i in range(30):
if sorted([int(m) for m in str(1<<i)])==cmp:return True
return False

c++

class Solution {
public:
bool reorderedPowerOf2(int n) {
string cmp=to_string(n);
sort(cmp.begin(),cmp.end());
for(int i=0;i<30;i++){
string cmp1=to_string(1<<i);
sort(cmp1.begin(),cmp1.end());
if(cmp1==cmp)return true;
}
return false;
}
};

Java

class Solution {
public boolean reorderedPowerOf2(int n) {
char[] cmp=String.valueOf(n).toCharArray();
Arrays.sort(cmp);
for(int i=0;i<30;i++){
char[] cmp1=String.valueOf(1<<i).toCharArray();
Arrays.sort(cmp1);
if(Arrays.equals(cmp1,cmp))return true;
}
return false;
}
}

Js

/**
* @param {number} n
* @return {boolean}
*/
var reorderedPowerOf2 = function(n) {
let cmp=n.toString().split("").sort().join("");
for(let i=0;i<30;i++)
if((1<<i).toString().split("").sort().join("")===cmp)return true;
return false;
};

posted @ 2021-10-28 11:37  XXXSANS  阅读(37)  评论(0编辑  收藏  举报