Problem
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:
|
1 2 |
<strong>Input: </strong><span id="example-input-5-1">46</span> <strong>Output: </strong><span id="example-output-5">true</span> |
Note:
1 <= N <= 10^9
Solution: HashTable
Compare the counter of digit string with that of all power of 2s.
e.g. 64 -> {4: 1, 6: 1} == 46 {4:1, 6: 1}
Time complexity: O(1)
Space complexity: O(1)
C++
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Author: Huahua class Solution { public: bool reorderedPowerOf2(int N) { auto m = countMap(N); for (int i = 0; i < 31; ++i) if (m == countMap(1 << i)) return true; return false; } private: map<int, int> countMap(int n) { map<int, int> m; while (n) { ++m[n % 10]; n /= 10; } return m; } }; |