亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go lang:從一組數字中搜索x位數字,為什么需要很長時間才能執行?

Go lang:從一組數字中搜索x位數字,為什么需要很長時間才能執行?

Go
回首憶惘然 2021-12-27 16:00:41
我試圖制作從一組數字中找到 x 位數字的小程序,例如:我想從1 - 1000000000 中找到第 89位數字。這是我的代碼:https : //play.golang.org/p/93yh_urX16package mainimport (    "fmt"    "strconv")var bucket stringfunc 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] ) )}有誰知道,我犯了什么錯誤?我需要一些建議來改進此代碼。
查看完整描述

1 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

你的程序非常非常低效。user1431317 的程序效率很低。


簡單地計算價值。它只需要幾納秒的 CPU 時間和一些內存分配,即使是大到 9,223,372,036,854,775,807 的數字索引(95.6 納秒和我的計算機上的 2 次分配)。例如,


package main


import (

    "fmt"

    "math"

    "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 {

    // There are 9 one digit positive integers, 90 two digit,

    // 900 three digit, and so on.

    if i <= 0 {

        return "0"

    }

    j := int64(1)

    w := 1

    for ; ; w++ {

        t := j + 9*int64(math.Pow10(w-1))*int64(w)

        if 0 > t || t > i {

            break

        }

        j = t

    }

    k := i - j

    n := k / int64(w)

    m := k % int64(w)

    d := strconv.FormatInt(int64(math.Pow10(w-1))+n, 10)[m]

    return string(d)

}


func main() {

    tests := []int64{

        0, 1, 2, 3, 4, 5, 6, 7, 8, 9,

        10, 11, 12, 13,

        88, 89,

        188, 189, 190, 191, 192,

        math.MaxInt32, math.MaxInt64,

    }

    for _, n := range tests {

        fmt.Println(n, digit(n))

    }

}

輸出:


0 0

1 1

2 2

3 3

4 4

5 5

6 6

7 7

8 8

9 9

10 1

11 0

12 1

13 1

88 4

89 9

188 9

189 9

190 1

191 0

192 0

2147483647 2

9223372036854775807 9


查看完整回答
反對 回復 2021-12-27
  • 1 回答
  • 0 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號