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

1 Answer

0 votes
package main

import (
    "fmt"
)

// FindPreviousDigit returns the digit that comes before the target digit
// when scanning the number from right to left.
// If the target is not found or has no previous digit, it returns -1.
func FindPreviousDigit(number, target int) int {
    for number > 0 {
        current := number % 10
        number /= 10

        if current == target {
            if number > 0 {
                return number % 10
            }
            return -1
        }
    }
    
    return -1
}

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

    result := FindPreviousDigit(number, target)

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


/*
run:

The digit before 7 in 8902741 is 2.

*/

 



answered Oct 22 by avibootz
edited Oct 22 by avibootz
...