본문 바로가기
나는 이렇게 학습한다/Algorithm & SQL

0206. Find the nth Digit of a Number

by daco2020 2023. 2. 7.

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, return -1
  • Keep in mind that 42 = 00042. This means that findDigit(42, 5) would return 0

Examples(num, nth --> output)

5673, 4 --> 5
129, 2 --> 2
-2825, 3 --> 8
-456, 4 --> 0
0, 20 --> 0
65, 0 --> -1
24, -8 --> -1



Solution:

def find_digit(num, nth):
    if nth < 1:
        return -1
    num = str(abs(num))
    if len(num) < nth:
        return 0
    return int(num[len(num)-nth:len(num)-nth+1])


'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

0209. Sort Out The Men From Boys  (0) 2023.02.09
0207. Divide and Conquer  (0) 2023.02.08
0205. pick a set of first elements  (0) 2023.02.05
0204. Filter the number  (0) 2023.02.04
0203. Parse float  (0) 2023.02.03