400. Nth Digit

題目:

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...

思路:

第幾層 數字 共有幾個數字 化為公式
1 1 ~ 9 9 X 1 9 X 10(1-1) X 1
2 10 ~ 99 90 X 2 9 X 10(2-1) X 2
3 100 ~ 999 900 X 3 9 X 10(3-1) X 3
4 1000 ~ 9999 9000 X 4 9 X 10(4-1) X 4
i 10(i-1) ~ 10i-1 9 X 10(i-1) X i 9 X 10(i-1) X i

找到n在第幾層,第幾個數字

pseudocode:

使用到的語法:

method: ceil 無條件進位,用於float

程式碼:

def find_nth_digit(n)
    i = 1
    while true #while 迴圈將n依次減掉越低層的數字量,找到n落在第i層
        if n > 9 * (10 ** (i-1)) * i
           n -= 9 * (10 ** (i-1)) * i
        else
            break
        end
        i += 1
    end
    x = (n.to_f/i.to_f).ceil
    current_num = (10 **(i-1)) + x -1
    index = (n-1) % i
    num_array = current_num.to_s.split("")
    return num_array[index].to_i
end

results matching ""

    No results matching ""