@@ -40,19 +40,12 @@ Traverse all the permutations of N, and examine each of them whether it is power
40
40
``` cpp
41
41
// OJ: https://leetcode.com/problems/reordered-power-of-2/
42
42
// Author: github.com/lzl124631x
43
- // Time: O(lg(N)! * log(N)),
44
- // where lg(N) is number of digits in N base-10,
45
- // and log(N) is number of digits in N base-2.
46
- // O(lg(N)!) is because of permutation, log(N) is because of testing `isPow2`.
43
+ // Time: O(lg(N)!)
47
44
// Space: O(lg(N))
48
45
class Solution {
49
46
private:
50
47
bool isPow2(long long N) {
51
- while (N != 1) {
52
- if (N % 2) return false;
53
- N /= 2;
54
- }
55
- return true;
48
+ return (N & (N - 1)) == 0;
56
49
}
57
50
string num;
58
51
bool dfs(int start) {
@@ -80,7 +73,7 @@ public:
80
73
81
74
## Solution 2. Counting
82
75
83
- There are only 32 possible powers of 2. Count the digits of N and compare the counts with those of a power of 2.
76
+ There are only 32 possible powers of 2. Count the digits of `N` and compare the counts with those of a power of 2.
84
77
85
78
```cpp
86
79
// OJ: https://leetcode.com/problems/reordered-power-of-2/
@@ -91,8 +84,8 @@ There are only 32 possible powers of 2. Count the digits of N and compare the co
91
84
// Space: O(lg(N))
92
85
class Solution {
93
86
private:
94
- vector <int> count(int N) {
95
- vector <int> cnt(10, 0) ;
87
+ array <int, 10 > count(int N) {
88
+ array <int, 10 > cnt = {} ;
96
89
while (N) {
97
90
cnt[N % 10]++;
98
91
N /= 10;
@@ -104,7 +97,7 @@ public:
104
97
auto cnt = count(N);
105
98
for (int i = 0; i < 31; ++i) {
106
99
auto c = count(1 << i);
107
- if (equal( cnt.begin(), cnt.end(), c.begin()) ) return true;
100
+ if (cnt == c ) return true;
108
101
}
109
102
return false;
110
103
}
0 commit comments