[leetcode] (周赛)869. 重新排序得到 2 的幂
枚举排列,然后验证。比较暴力。
其实好一点的做法应该反过来,先把int范围下的2的N幂算出来,然后一个一个验证给出的数能不能拼成。
class Solution {
public Integer[] nextPermutation(Integer[] nums) {
if (nums.length == 1) {
return new Integer[]{};
}
int p = -1;
for (int i = nums.length - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
p = i;
break;
}
}
if (p != -1) {
int tmp = nums[p];
int q = nums.length - 1;
while (nums[q] <= tmp) {
q--;
}
nums[p] = nums[q];
nums[q] = tmp;
reverse(p + 1, nums);
} else {
return new Integer[]{};
}
return nums;
}
public void reverse(int k, Integer[] nums) {
if (k >= nums.length) return;
int i = k;
int j = nums.length - 1;
while (i < j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
i++;
j--;
}
}
public boolean reorderedPowerOf2(int N) {
if (N == 0) {
return false;
}
String s = Integer.toString(N);
int[] p = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for (int i = 0; i < s.length(); i++) {
p[s.charAt(i) - '0']++;
}
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < p[i]; j++) {
list.add(i);
}
}
Integer[] nums = list.stream().toArray(Integer[]::new);
StringBuilder origin = new StringBuilder();
for (int i = 0; i < nums.length; i++) {
origin.append(nums[i]);
}
while (nums[0] == 0) {
nums = nextPermutation(nums);
}
int flag = 0;
while (true) {
if (nums.length == 0) {
break;
}
StringBuilder st = new StringBuilder();
for (int i = 0; i < nums.length; i++) {
st.append(nums[i]);
}
Integer num = Integer.valueOf(st.toString());
double ans = Math.log(num) / Math.log(2);
if (isNotDouble(ans)) {
return true;
}
nums = nextPermutation(nums);
}
return false;
}
public static boolean isNotDouble(Double x) {
int i = x.intValue();
return x - i < 0.000001;
}
}
这周周赛就做出来这两个。。。水平还是太低啊,哎