Skip to content

Latest commit

 

History

History
111 lines (95 loc) · 2.11 KB

869. Reordered Power of 2.md

File metadata and controls

111 lines (95 loc) · 2.11 KB

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 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

Solution

  • 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;
        }
        

  • 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;
    }