首頁 > 後端開發 > Golang > 主體

如何列印與前面的數字不同的數字?

WBOY
發布: 2024-02-06 09:51:09
轉載
968 人瀏覽過

如何列印與前面的數字不同的數字?

問題內容

例如,如果我有數字 35565,則輸出為 3565。

所以,我的程式碼片段得到了個位數,但我不知道如何保留前一個數字以與下一個數字進行檢查。

for {
num = num / 10
fmt.Print(num)
        
if num/10 == 0 {
    break
}
}
登入後複製


正確答案


這種方法從右到左將數字分解為數字,將它們儲存為整數切片,然後從左到右迭代這些數字以建構具有“連續唯一”數字的數字。

我最初嘗試從左到右分解數字,但不知道如何處理佔位零;從右到左分解它,我知道如何捕獲這些零。

// unique removes sequences of repeated digits from non-negative x,
// returning only "sequentially unique" digits:
// 12→12, 122→12, 1001→101, 35565→3565.
//
// Negative x yields -1.
func unique(x int) int {
    switch {
    case x < 0:
        return -1
    case x <= 10:
        return x
    }

    // -- Split x into its digits
    var (
        mag     int   // the magnitude of x
        nDigits int   // the number of digits in x
        digits  []int // the digits of x
    )

    mag = int(math.Floor(math.Log10(float64(x))))
    nDigits = mag + 1

    // work from right-to-left to preserve place-holding zeroes
    digits = make([]int, nDigits)
    for i := nDigits - 1; i >= 0; i-- {
        digits[i] = x % 10
        x /= 10
    }

    // -- Build new, "sequentially unique", x from left-to-right
    var prevDigit, newX int

    for _, digit := range digits {
        if digit != prevDigit {
            newX = newX*10 + digit
        }
        prevDigit = digit
    }

    return newX
}
登入後複製

這是一個go playground 進行測試

可以透過翻轉開頭的負號並在末尾恢復它來適應處理負數。

以上是如何列印與前面的數字不同的數字?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!