Skip to content

Commit 63cdece

Browse files
authored
Update sort-integers-by-the-power-value.cpp
1 parent 821a026 commit 63cdece

File tree

1 file changed

+16
-30
lines changed

1 file changed

+16
-30
lines changed

C++/sort-integers-by-the-power-value.cpp

Lines changed: 16 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -15,23 +15,16 @@ class Solution {
1515

1616
private:
1717
int power_value(int x) {
18-
int y = x;
19-
if (!Solution::dp_.count(y)) {
20-
int result = 0;
21-
while (x > 1) {
22-
++result;
23-
if (x & 1) {
24-
x = 3 * x + 1;
25-
} else {
26-
x >>= 1;
27-
}
28-
if (Solution::dp_.count(x)) {
29-
result += Solution::dp_[x];
30-
break;
31-
}
18+
int y = x, result = 0;
19+
while (x > 1 && !Solution::dp_.count(x)) {
20+
++result;
21+
if (x & 1) {
22+
x = 3 * x + 1;
23+
} else {
24+
x >>= 1;
3225
}
33-
Solution::dp_[y] = result;
3426
}
27+
Solution::dp_[y] = result + Solution::dp_[x];
3528
return Solution::dp_[y];
3629
}
3730

@@ -55,23 +48,16 @@ class Solution2 {
5548

5649
private:
5750
int power_value(int x) {
58-
int y = x;
59-
if (!Solution2::dp_.count(y)) {
60-
int result = 0;
61-
while (x > 1) {
62-
++result;
63-
if (x & 1) {
64-
x = 3 * x + 1;
65-
} else {
66-
x >>= 1;
67-
}
68-
if (Solution2::dp_.count(x)) {
69-
result += Solution2::dp_[x];
70-
break;
71-
}
51+
int y = x, result = 0;
52+
while (x > 1 && !Solution2::dp_.count(x)) {
53+
++result;
54+
if (x & 1) {
55+
x = 3 * x + 1;
56+
} else {
57+
x >>= 1;
7258
}
73-
Solution2::dp_[y] = result;
7459
}
60+
Solution2::dp_[y] = result + Solution2::dp_[x];
7561
return Solution2::dp_[y];
7662
}
7763

0 commit comments

Comments
 (0)