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

1 Answer

0 votes
import Foundation

/// Finds the digit that comes before the target digit when scanning from right to left.
/// Returns: The digit that comes before the target, or -1 if not found or no previous digit.
func findPreviousDigit(in number: Int, target: Int) -> Int {
    var num = number

    while num > 0 {
        let current = num % 10
        num /= 10

        if current == target {
            return num > 0 ? num % 10 : -1
        }
    }

    return -1
}

let number = 8902741
let target = 7
let result = findPreviousDigit(in: number, target: target)

if result != -1 {
    print("The digit before \(target) in \(number) is \(result).")
} else {
    print("The digit \(target) is not found or has no previous digit in \(number).")
}



/*
run:

The digit before 7 in 8902741 is 2.

*/

 



answered Oct 22 by avibootz
...