[LeetCode] 869. Reordered Power of 2
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 <= N <= 10^9
重新排序得到 2 的幂。
给定正整数 N ,我们按任何顺序(包括原始顺序)将数字重新排序,注意其前导数字不能为零。
如果我们可以通过上述方式得到 2 的幂,返回 true;否则,返回 false。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reordered-power-of-2
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道数学题但是个人觉得题意解释的不是非常清楚。题意是请你对 input 数字的 digits 做任意排序,看看是否存在某个排序的结果是 2 的幂。因为题目给的数据范围的上界是到 10^9,而且10^9 < 2^31,所以我们不需要担心越界的问题。
做法是首先把 input 数字变成一个 char array,排序,并再转换成字符串。接着我遍历 2 的每个幂,并把 2 的每个幂都变成一个排好序的字符串与之前 input 转换而来的字符串进行比较,看看是否能找到匹配,若找不到就只能 return false 了。题目中没有提到可以对 2 的幂的结果进行排序,但是讨论区高票答案都是对 2 的幂进行了排序。
时间O(1) - 只做了31次比较
空间O(1) - char array几乎可以忽略不计
Java实现
1 class Solution { 2 public boolean reorderedPowerOf2(int N) { 3 char[] a1 = String.valueOf(N).toCharArray(); 4 Arrays.sort(a1); 5 String s1 = new String(a1); 6 7 // only 2^31 is smaller than 10^9 8 for (int i = 0; i < 31; i++) { 9 char[] a2 = String.valueOf((int) (1 << i)).toCharArray(); 10 Arrays.sort(a2); 11 String s2 = new String(a2); 12 if (s1.equals(s2)) { 13 return true; 14 } 15 } 16 return false; 17 } 18 }
JavaScript实现
1 /** 2 * @param {number} n 3 * @return {boolean} 4 */ 5 var reorderedPowerOf2 = function(n) { 6 let res = n.toString().split("").sort().join(""); 7 for (let i = 0; i < 31; i++) { 8 if ((1 << i).toString().split("").sort().join("") === res) { 9 return true; 10 } 11 } 12 return false; 13 };