首頁  >  文章  >  後端開發  >  如何列印與前面的數字不同的數字?

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

WBOY
WBOY轉載
2024-02-06 09:51:09969瀏覽

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

問題內容

例如,如果我有數字 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刪除