Welcome to Subscribe On Youtube

869. Reordered Power of 2

Description

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.

 

Example 1:

Input: n = 1
Output: true

Example 2:

Input: n = 10
Output: false

 

Constraints:

  • 1 <= n <= 109

Solutions

  • class Solution {
        public boolean reorderedPowerOf2(int n) {
            String s = convert(n);
            for (int i = 1; i <= Math.pow(10, 9); i <<= 1) {
                if (s.equals(convert(i))) {
                    return true;
                }
            }
            return false;
        }
    
        private String convert(int n) {
            char[] cnt = new char[10];
            for (; n > 0; n /= 10) {
                cnt[n % 10]++;
            }
            return new String(cnt);
        }
    }
    
  • class Solution {
    public:
        bool reorderedPowerOf2(int n) {
            vector<int> s = convert(n);
            for (int i = 1; i <= pow(10, 9); i <<= 1)
                if (s == convert(i))
                    return true;
            return false;
        }
    
        vector<int> convert(int n) {
            vector<int> cnt(10);
            for (; n; n /= 10) ++cnt[n % 10];
            return cnt;
        }
    };
    
  • class Solution:
        def reorderedPowerOf2(self, n: int) -> bool:
            def convert(n):
                cnt = [0] * 10
                while n:
                    n, v = divmod(n, 10)
                    cnt[v] += 1
                return cnt
    
            i, s = 1, convert(n)
            while i <= 10**9:
                if convert(i) == s:
                    return True
                i <<= 1
            return False
    
    
  • func reorderedPowerOf2(n int) bool {
    	convert := func(n int) []byte {
    		cnt := make([]byte, 10)
    		for ; n > 0; n /= 10 {
    			cnt[n%10]++
    		}
    		return cnt
    	}
    	s := convert(n)
    	for i := 1; i <= 1e9; i <<= 1 {
    		if bytes.Equal(s, convert(i)) {
    			return true
    		}
    	}
    	return false
    }
    

All Problems

All Solutions