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:
parent
9754709bd4
commit
e69372dbef
1 changed files with 43 additions and 0 deletions
43
go/count-the-number-of-powerful-integers.go
Normal file
43
go/count-the-number-of-powerful-integers.go
Normal 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)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue