Skip to content

Commit 7a90f37

Browse files
committed
Update 0483 solution
1 parent 555737b commit 7a90f37

File tree

2 files changed

+26
-47
lines changed

2 files changed

+26
-47
lines changed

leetcode/0483.Smallest-Good-Base/483. Smallest Good Base.go

Lines changed: 13 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,23 @@ package leetcode
22

33
import (
44
"math"
5+
"math/bits"
56
"strconv"
67
)
78

89
func smallestGoodBase(n string) string {
9-
num, _ := strconv.ParseUint(n, 10, 64)
10-
for bit := uint64(math.Log2(float64(num))); bit >= 1; bit-- {
11-
low, high := uint64(2), uint64(math.Pow(float64(num), 1.0/float64(bit)))
12-
for low < high {
13-
mid := uint64(low + (high-low)>>1)
14-
sum := findBase(mid, bit)
15-
if sum == num {
16-
return strconv.FormatUint(mid, 10)
17-
} else if sum > num {
18-
high = mid - 1
19-
} else {
20-
low = mid + 1
21-
}
10+
nVal, _ := strconv.Atoi(n)
11+
mMax := bits.Len(uint(nVal)) - 1
12+
for m := mMax; m > 1; m-- {
13+
k := int(math.Pow(float64(nVal), 1/float64(m)))
14+
mul, sum := 1, 1
15+
for i := 0; i < m; i++ {
16+
mul *= k
17+
sum += mul
18+
}
19+
if sum == nVal {
20+
return strconv.Itoa(k)
2221
}
2322
}
24-
return strconv.FormatUint(num-1, 10)
25-
}
26-
27-
// 计算 k^m + k^(m-1) + ... + k + 1
28-
func findBase(mid, bit uint64) uint64 {
29-
sum, base := uint64(1), uint64(1)
30-
for i := uint64(1); i <= bit; i++ {
31-
base *= mid
32-
sum += base
33-
}
34-
return sum
23+
return strconv.Itoa(nVal - 1)
3524
}

website/content/ChapterFour/0400~0499/0483.Smallest-Good-Base.md

Lines changed: 13 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -104,37 +104,27 @@ package leetcode
104104

105105
import (
106106
"math"
107+
"math/bits"
107108
"strconv"
108109
)
109110

110111
func smallestGoodBase(n string) string {
111-
num, _ := strconv.ParseUint(n, 10, 64)
112-
for bit := uint64(math.Log2(float64(num))); bit >= 1; bit-- {
113-
low, high := uint64(2), uint64(math.Pow(float64(num), 1.0/float64(bit)))
114-
for low < high {
115-
mid := uint64(low + (high-low)>>1)
116-
sum := findBase(mid, bit)
117-
if sum == num {
118-
return strconv.FormatUint(mid, 10)
119-
} else if sum > num {
120-
high = mid - 1
121-
} else {
122-
low = mid + 1
123-
}
112+
nVal, _ := strconv.Atoi(n)
113+
mMax := bits.Len(uint(nVal)) - 1
114+
for m := mMax; m > 1; m-- {
115+
k := int(math.Pow(float64(nVal), 1/float64(m)))
116+
mul, sum := 1, 1
117+
for i := 0; i < m; i++ {
118+
mul *= k
119+
sum += mul
120+
}
121+
if sum == nVal {
122+
return strconv.Itoa(k)
124123
}
125124
}
126-
return strconv.FormatUint(num-1, 10)
125+
return strconv.Itoa(nVal - 1)
127126
}
128127

129-
// 计算 k^m + k^(m-1) + ... + k + 1
130-
func findBase(mid, bit uint64) uint64 {
131-
sum, base := uint64(1), uint64(1)
132-
for i := uint64(1); i <= bit; i++ {
133-
base *= mid
134-
sum += base
135-
}
136-
return sum
137-
}
138128

139129
```
140130

0 commit comments

Comments
 (0)