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

1 Answer

0 votes
import Foundation

func findNextDigit(in number: Int, target: Int) -> Int {
    var num = number
    var next = -1

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

        if current == target {
            return next
        }

        next = current
    }

    return -1
}

let number = 8902741
let target = 2
let result = findNextDigit(in: number, target: target)

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



/*
run:

The digit after 2 in 8902741 is 7.

*/

 



answered Oct 19 by avibootz
...