URL: https://leetcode.com/problems/count-the-number-of-powerful-integers/ Signed-off-by: Matej Focko <me@mfocko.xyz>
43 lines
767 B
Go
43 lines
767 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"math"
|
|
)
|
|
|
|
func numberOfPowerfulInt(start int64, finish int64, limit int, s string) int64 {
|
|
calculate := func(x string) int64 {
|
|
if len(x) < len(s) {
|
|
return 0
|
|
}
|
|
|
|
if len(x) == len(s) {
|
|
if x >= s {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|
|
|
|
count := int64(0)
|
|
|
|
prefixLength := len(x) - len(s)
|
|
for i := 0; i < prefixLength; i++ {
|
|
if limit < int(x[i])-'0' {
|
|
count += int64(math.Pow(float64(limit+1), float64(prefixLength-i)))
|
|
return count
|
|
}
|
|
|
|
count += int64(int(x[i])-'0') * int64(math.Pow(float64(limit+1), float64(prefixLength-1-i)))
|
|
}
|
|
|
|
if x[len(x)-len(s):] >= s {
|
|
count++
|
|
}
|
|
|
|
return count
|
|
|
|
}
|
|
|
|
_start, _finish := fmt.Sprint(start-1), fmt.Sprint(finish)
|
|
return calculate(_finish) - calculate(_start)
|
|
}
|