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 .
Solution 打表,将所有二的指数全部计算出来,并用数组统计各个数字出现的频率。 然后同样统计n中各个数字出现的频率。
如果两者中有频率完全相同的情况,则返回true,反之返回false。
Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 class Solution { public boolean reorderedPowerOf2 (int n) { int [] reorders = new int [10 ]; int m = 1 , digits = 0 ; for (int i = n; i > 0 ; i/=10 ){ reorders[i % 10 ]++; digits++; } int size = 0 ; List<Integer[]> powerOfTwo = new ArrayList <>(); while (m > 0 && size <= digits){ size = 0 ; Integer[] bin = new Integer [10 ]; Arrays.fill(bin, 0 ); for (int i = m; i > 0 ; i/=10 ){ size++; bin[i % 10 ]++; } if (size == digits) powerOfTwo.add(bin); m *= 2 ; } for (Integer[] bin : powerOfTwo) if (check(bin, reorders)) return true ; return false ; } private boolean check (Integer[] bin, int [] reorders) { for (int i = 0 ; i < bin.length; i++) if (bin[i] != reorders[i]) return false ; return true ; } }
Solution 2 回溯,遍历计算可以组成的所有数字。 打表记录所有二的指数并记录在哈希表内,如果所有组成数字中有哈希表内的数字则返回true,反之返回false。
Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 class Solution { HashSet<Integer> visited, set, numbers; List<Integer> arr, res; public boolean reorderedPowerOf2 (int n) { int m = 1 ; set = new HashSet <>(); visited = new HashSet <>(); numbers = new HashSet <>(); res = new ArrayList <Integer>(); while (m > 0 ){ set.add(m); m *= 2 ; } arr = new ArrayList <>(); while (n > 0 ){ arr.add(n % 10 ); n /= 10 ; } for (int i = 0 ; i< arr.size(); i++){ if (arr.get(i) == 0 ) continue ; visited.add(i); reorder(arr.get(i)); visited.remove(i); } for (int num : res) if (set.contains(num)) return true ; return false ; } private void reorder (int num) { if (visited.size() == arr.size()){ res.add(num); return ; }; if (numbers.contains(num)) return ; numbers.add(num); for (int i = 0 ; i < arr.size(); i++){ if (visited.contains(i)) continue ; int next = num * 10 + arr.get(i); visited.add(i); reorder(next); visited.remove(i); } } }