How to print a number that is different from the previous number?

WBOY
Release: 2024-02-06 09:51:09
forward
968 people have browsed it

How to print a number that is different from the previous number?

Question content

For example, if I have the number 35565, the output is 3565.

So, my code snippet gets the single digits, but I don't know how to keep the previous number to check with the next number.

for {
num = num / 10
fmt.Print(num)
        
if num/10 == 0 {
    break
}
}
Copy after login


Correct answer


This method breaks the number into numbers from right to left, stores them as integer slices, and then iterates over the numbers from left to right to Construct numbers with "consecutively unique" digits.

I initially tried breaking the number from left to right, but didn't know how to handle the placeholder zeros; breaking it up right to left, I knew how to capture those zeros.

// 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
}
Copy after login

This is a go playground for testing.

Can be adapted to handle negative numbers by flipping the negative sign at the beginning and restoring it at the end.

The above is the detailed content of How to print a number that is different from the previous number?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!