869. Reordered Power of 2
1. Question
You are given an 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 so that the resulting number is a power of two.
2. Examples
Example 1:
Input: n = 1
Output: true
Example 2:
Input: n = 10
Output: false
Example 3:
Input: n = 16
Output: true
Example 4:
Input: n = 24
Output: false
Example 5:
Input: n = 46
Output: true
3. Constraints
- 1 <= n <= 109
4. References
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reordered-power-of-2 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
5. Solutions
一个讨巧的方法,排序
class Solution {
public boolean reorderedPowerOf2(int n) {
char[] ch = String.valueOf(n).toCharArray();
// 将数字按照字典顺序升序排序,即每个数字从小到大排序
Arrays.sort(ch);
for (int i = 1; i < 1e9; i *= 2) {
char[] ans = String.valueOf(i).toCharArray();
Arrays.sort(ans);
if (Arrays.equals(ch, ans)) {
return true;
}
}
return false;
}
}