Home > Software design >  How to print each digit of the number different from the one that precedes it?
How to print each digit of the number different from the one that precedes it?

Time:01-09

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

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

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

CodePudding user response:

This approach breaks down a number into its digits from right-to-left, storing them as a slice of ints, then iterates those digits from left-to-right to build up the number with "sequentially unique" digits.

I originally tried to break down the number from left-to-right but couldn't figure out how to handle place-holding zeroes; breaking it down from right-to-left, I know how to capture those zeroes.

// 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
}

Here's a Go Playground with a test.

This could be adapted to deal with negative numbers by flipping the negative sign at the beginning and restoring it at the end.

  • Related