-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
57 lines (52 loc) · 1.35 KB
/
main.cpp
File metadata and controls
57 lines (52 loc) · 1.35 KB
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
52
53
54
55
56
57
// Source: https://leetcode.com/problems/reordered-power-of-2
// Title: Reordered Power of 2
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 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 <= 10^9`
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <array>
using namespace std;
// First find the digits of n.
// Check all power of 2 and check if the digits distribution is equal.
class Solution {
public:
bool reorderedPowerOf2(int n) {
auto count = [](int x) -> array<int, 10> {
auto ret = array<int, 10>();
while (x > 0) {
ret[x % 10]++;
x /= 10;
}
return ret;
};
auto digits = count(n);
for (auto p = 0; p < 31; p++) {
if (digits == count(1 << p)) {
return true;
}
}
return false;
}
};