How to find the digit next to a given digit in a number with Go

1 Answer

0 votes
package main

import (
    "fmt"
)

// FindNextDigit returns the digit that comes after the target digit
// when scanning the number from right to left.
// If the target is not found or has no next digit, it returns -1.
func FindNextDigit(number, target int) int {
    next := -1

    for number > 0 {
        current := number % 10
        number /= 10

        if current == target {
            return next
        }

        next = current
    }

    return -1
}

func main() {
    number := 8902741
    target := 2

    result := FindNextDigit(number, target)

    if result != -1 {
        fmt.Printf("The digit after %d in %d is %d.\n", target, number, result)
    } else {
        fmt.Printf("The digit %d is not found or has no next digit in %d.\n", target, number)
    }
}



/*
run:

The digit after 2 in 8902741 is 7.

*/

 



answered Oct 18 by avibootz
...