400. Nth Digit


做题历程:

  1. 2016/Oct/20 本题应该算是第一次做,本次耗时25分钟独立解出

其实严格意义不算独立解出了,毕竟有一点瑕疵,没有把其中一个value改成long。本题的思路不是很好叙述,代码会更清晰,但是可以说一下大致思路:

  1. 要根据n定位该n值所对应的digit是一个几位数
  2. 然后根据这个再算n所属的整数是多少
  3. 再计算n在这个整数中属于第几个digit

根据以上应该就能得出答案,代码如下:

class Solution {
public:
    int findNthDigit(int n) {
        int num_of_digit = 1;
        long start = 9;
        while (n > start * num_of_digit) {
            n -= start * num_of_digit;
            start *= 10;
            num_of_digit++;
        }
        long base = pow(10, num_of_digit - 1);
        long bias = (n - 1) / num_of_digit;
        int digit_index = (n - 1) % num_of_digit;

        string int_str = to_string(base + bias);
        return int_str[digit_index] - '0';
    }
};

results matching ""

    No results matching ""