• 400. 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).

    Example 1:

    Input:
    3
    
    Output:
    3
    

    Example 2:

    Input:
    11
    
    Output:
    0
    
    Explanation:
    The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.

    Approach #1: Math. [Java]

    class Solution {
        public int findNthDigit(int n) {
            int len = 1;
            int start = 1;
            long count = 9;
            
            while (n > len * count) {
                n -= len * count;
                len++;
                start *= 10;
                count *= 10;
            }
            
            int num = start + (n - 1) / len;
            String s = Integer.toString(num);
            return Character.getNumericValue(s.charAt((n-1) % len));
        }
    }
    

      

    Analysis:

    Straight forward way to solve the problem in 3 steps:

    1. find the length of the number where the nth digit is from.

    2. find the actual number where the nth digit is from

    3. find the nth digit and return.

    The reason why we reduce 1 from n is to calibrate the difference between rank and natural number.

    We initialize 'start' as 1, which is the 1st element in the sequence. It is the same as an array, where the index should be now 0-based. Actually, we can subtract 1 from n at the very beginning.

    Reference:

    https://leetcode.com/problems/nth-digit/discuss/88363/Java-solution

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    LintCode 17.子集
    JS时间操作
    Ajax总结
    Ajax请求文件下载操作失败的原因和解决办法
    遍历Map的几种方式
    java获取文件大小的方法
    Ajax详细介绍
    第31课
    30-React JSX IN DEPTH
    28-React state提升、组件组合或继承
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10816365.html
Copyright © 2020-2023  润新知