Go lang:从一组数字中搜索x位数字,为什么需要很长时间才能执行?

我试图制作从一组数字中找到 x 位数字的小程序,例如:我想从1 - 1000000000 中找到第 89位数字。


这是我的代码:https : //play.golang.org/p/93yh_urX16


package main


import (


    "fmt"

    "strconv"


)


var bucket string


func main() {


    findDigits( 89, 1000000000 )


}


func findDigits( digits int, length int) {


    for i := 1; i <= length; i++ {


        bucket += strconv.Itoa(i)


    }


    fmt.Println( "The", digits, "th digit from 1", "-", length, "is :", string ( [] rune ( bucket )[digits - 1] ) )


}

有谁知道,我犯了什么错误?我需要一些建议来改进此代码。


回首忆惘然
浏览 145回答 1
1回答

弑天下

你的程序非常非常低效。user1431317 的程序效率很低。简单地计算价值。它只需要几纳秒的 CPU 时间和一些内存分配,即使是大到 9,223,372,036,854,775,807 的数字索引(95.6 纳秒和我的计算机上的 2 次分配)。例如,package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math"&nbsp; &nbsp; "strconv")// digit returns the ith digit from the sequence of// concatenated non-negative integers.// The sequence of digits is 01234567891011121314151617181920...func digit(i int64) string {&nbsp; &nbsp; // There are 9 one digit positive integers, 90 two digit,&nbsp; &nbsp; // 900 three digit, and so on.&nbsp; &nbsp; if i <= 0 {&nbsp; &nbsp; &nbsp; &nbsp; return "0"&nbsp; &nbsp; }&nbsp; &nbsp; j := int64(1)&nbsp; &nbsp; w := 1&nbsp; &nbsp; for ; ; w++ {&nbsp; &nbsp; &nbsp; &nbsp; t := j + 9*int64(math.Pow10(w-1))*int64(w)&nbsp; &nbsp; &nbsp; &nbsp; if 0 > t || t > i {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; j = t&nbsp; &nbsp; }&nbsp; &nbsp; k := i - j&nbsp; &nbsp; n := k / int64(w)&nbsp; &nbsp; m := k % int64(w)&nbsp; &nbsp; d := strconv.FormatInt(int64(math.Pow10(w-1))+n, 10)[m]&nbsp; &nbsp; return string(d)}func main() {&nbsp; &nbsp; tests := []int64{&nbsp; &nbsp; &nbsp; &nbsp; 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,&nbsp; &nbsp; &nbsp; &nbsp; 10, 11, 12, 13,&nbsp; &nbsp; &nbsp; &nbsp; 88, 89,&nbsp; &nbsp; &nbsp; &nbsp; 188, 189, 190, 191, 192,&nbsp; &nbsp; &nbsp; &nbsp; math.MaxInt32, math.MaxInt64,&nbsp; &nbsp; }&nbsp; &nbsp; for _, n := range tests {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(n, digit(n))&nbsp; &nbsp; }}输出:0 01 12 23 34 45 56 67 78 89 910 111 012 113 188 489 9188 9189 9190 1191 0192 02147483647 29223372036854775807 9
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go