给定正整数 N ,我们按任何顺序(包括原始顺序)将数字重新排序,注意其前导数字不能为零。
如果我们可以通过上述方式得到 2 的幂,返回 true;否则,返回 false。
示例 1:
输入:1
输出:true
示例 2:
输入:10
输出:false
示例 3:
输入:16
输出:true
示例 4:
输入:24
输出:false
示例 5:
输入:46
输出:true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reordered-power-of-2
看到题目时的第一感觉是使用dfs遍历所有可能然后进行匹配
方法一:将正整数N的每一位上的数放入数组中,然后对数组进行dfs生成数字
class Solution {
public static double result = 0;
public static boolean flag = false;
public static int[] arr = new int[100];
public static boolean[] bool = new boolean[100];
public boolean reorderedPowerOf2(int n) {
int size = 0;
while(n%10 != 0)
{
arr[size] = n%10;
bool[size] = true;
n = n/10;
++size;
}
dfs(arr,bool,0,size);
return flag;
}
public static void dfs(int[] arr,boolean[] bool, int length,int size){
if (length == size){
if (isValid(result)){
flag = true;
}
if(bool[length] == true)
return;
return;
}
if(length>size)
return;
for (int i = 0; i < size; i++) {
if (bool[i]){
result = result + arr[i] * Math.pow(10, length);
bool[i] = false;
dfs(arr,bool,length+1,size);
bool[i] = true;
result = result - arr[i] * Math.pow(10, length);
}
}
return;
}
public static boolean isValid(double n){
boolean f = false;
double a = 1;
while(a <= n){
if(a == n){
f = true;
break;
}
a *=2;
}
return f;
}
}
方法二:将正整数N与2的n次方的各个位置上的数字放入数组中,两个数组进行排序之后变成一个数组匹配问题
class Solution {
public boolean reorderedPowerOf2(int n) {
int size = 0;
for(int i = 0;i < 30;i++)
{
if(check((int)Math.pow(2,i),n))
return true;
}
return false;
}
public boolean check(int target,int n){
boolean flag = true;
int[] a = new int[10];
int[] b = new int[10];
int i = 0;
int j = 0;
for (int k = 0; k < a.length; k++) {
a[k] = 10;
b[k] = 10;
}
while(n != 0)
{
a[i++] = n%10;
n = n/10;
}
while(target != 0)
{
b[j++] = target%10;
target = target/10;
}
if (i != j) return false;
Arrays.sort(a);
Arrays.sort(b);
for(int x = 0;x < i+1;x++){
if(a[x] != b[x])
flag = false;
}
return flag;
}
}