004 Find the nth Digit of a Number
Published in
1 min readJun 16, 2021
Instructions:
Description
Complete the function that takes two numbers as input, num
and nth
and return the nth
digit of num
(counting from right to left).
Note
- If
num
is negative, ignore its sign and treat it as a positive value - If
nth
is not positive, return1
- Keep in mind that
42 = 00042
. This means thatfindDigit(42, 5)
would return0
Examples
findDigit(5673, 4) returns 5
findDigit(129, 2) returns 2
findDigit(-2825, 3) returns 8
findDigit(-456, 4) returns 0
findDigit(0, 20) returns 0
findDigit(65, 0) returns -1
findDigit(24, -8) returns -1
TryCode:
func findDigit(_ num:Int, _ nth: Int) -> Int { var numToString = "\\(num)" if nth <= 0 {
return -1
}else{ if numToString.count >= nth{
var offsetNumber = nth
offsetNumber.negate()
offsetNumber + 1
return
Int("\\(numToString[numToString.index(numToString.endIndex, offsetBy: offsetNumber)])" ) ?? 0
}else{ return 0 } }
}
BetterCode:
func findDigit(_ num: Int, _ nth: Int) -> Int {
let positive = abs(num)
guard nth > 0 else { return -1 }
guard positive > 0 else { return 0 }
guard nth > 1 else { return positive % 10 }
return findDigit(positive / 10, nth - 1)
}