go: add «2999. Count the Number of Powerful Integers»

URL:	https://leetcode.com/problems/count-the-number-of-powerful-integers/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-04-10 09:20:12 +02:00
parent 9754709bd4
commit e69372dbef
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,43 @@
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)
}