1. 程式人生 > >演算法練習week6--leetcode400

演算法練習week6--leetcode400

題目連結:https://leetcode.com/contest/5/problems/nth-digit/

題目: 
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, … 
Note: 
n is positive and will fit within the range of a 32-bit signed integer (n < 231).

思路: 
1~9 9個數 9*1=9個digit 
10~99 90個數 90*2=180個digit 
100~999 900個數 900*3=2700個digit 
10^k ~ k個9連成的數 9*10^k個數 (90*10^k)*k個digit

所以給點n,首先確定在幾位數之間,如在1000~9999還是在其他之間?然後確定是該區間的哪個數?最後確定是該數字的哪個digit? 
注意防止溢位。

演算法:

  public int findNthDigit(int n) {
        int k = 1;
        long len = 0;
        while (n > len) {
            len += (int) (9 * k * Math.pow(10, k - 1));
            k++;
        }
        k--;
        len -= (int) (9 * k * Math.pow(10, k - 1));
        // ————前部分
        int num = 0;
        if ((n - len) % k == 0) {
            num = (int) ((int) Math.pow(10, k - 1) + (n - len) / k - 1);
            String s = String.valueOf(num);
            return Integer.parseInt("" + s.charAt(s.length() - 1));
        } else {
            num = (int) ((int) Math.pow(10, k - 1) + (n - len) / k);
            String s = String.valueOf(num);
            return Integer.parseInt("" + s.charAt((int) ((n - len) % k - 1)));
        }
}