leetcode Daily Challenge on March 21th, 2021.
Difficulty : Medium
Related Topics : Math
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 of2
.Input: 1 Output: true
Input: 10 Output: false
Input: 16 Output: true
Input: 24 Output: false
Input: 46 Output: true
1 <= N <= 10^9
- mine
- Java
- Bit Manipulation
Runtime: 1 ms, faster than 96.64%, Memory Usage: 35.6 MB, less than 91.60% of Java online submissions
//O(1)time //O(1)space public boolean reorderedPowerOf2(int N) { int[] t = counter(N); for (int i = 0; i < 32; i++) if (check(t, counter(1 << i))) return true; return false; } public int[] counter(int N) { int[] arr = new int[10]; while(N > 0){ arr[N % 10]++; N = N / 10; } return arr; } public boolean check(int[] a, int[] b){ for(int i = 0; i < a.length; i++){ if(a[i] != b[i]) return false; } return true; }
- Bit Manipulation
- Java
- the most votes
Runtime: 1 ms, faster than 96.64%, Memory Usage: 35.7 MB, less than 88.24% of Java online submissions
//O(1)time //O(1)space public boolean reorderedPowerOf2(int N) { long c = counter(N); for (int i = 0; i < 32; i++) if (counter(1 << i) == c) return true; return false; } public long counter(int N) { long res = 0; for (; N > 0; N /= 10) res += (int)Math.pow(10, N % 10); return res; }