剑指offer44 数字序列中某一位的数字

package com.example.lettcode.offer;

/**
 * @Class FindNthDigit
 * @Description 剑指offer44 数字序列中某一位的数字
 * 数字以0123456789101112131415…的格式序列化到一个字符序列中。
 * 在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
 * 请写一个函数,求任意第n位对应的数字。
 * 示例 1:
 * 输入:n = 3
 * 输出:3
 * <p>
 * 示例 2:
 * 输入:n = 11
 * 输出:0
 * <p>
 * 限制:
 * 0 <= n < 2^31
 * @Author
 * @Date 2020/7/20
 **/
public class FindNthDigit {   
}
/**
 * 解法:
 * 1. 确定n所在数字的位数,记为digit;
 * 2. 确定n所在的数字,记为num;
 * 3. 确定n是num中的哪一数位,并返回结果。
 */
public static int findNthDigit(int n) {

        int digit = 1;      // n所在数字的位数
        long start = 1;     // 相同位数数字的第一个数字
        long count = 9;
        // 确定n所在数字的位数,记为digit;
        while (n > count) { // 1.
            n -= count;
            digit += 1;
            start *= 10;
            count = digit * start * 9;
        }
        // 确定n所在的数字,记为num;
        long num = start + (n - 1) / digit; // 2.
        return Long.toString(num).charAt((n - 1) % digit) - '0'; // 3.
    }
// 测试用例
public static void main(String[] args) {
	int n = 3;
	int ans = findNthDigit(n);
	System.out.println("FindNthDigit demo01 result:" + ans);

	n = 11;
	ans = findNthDigit(n);
	System.out.println("FindNthDigit demo01 result:" + ans);

	n = 120;
	ans = findNthDigit(n);
	System.out.println("FindNthDigit demo01 result:" + ans);

	n = 1200;
	ans = findNthDigit(n);
	System.out.println("FindNthDigit demo01 result:" + ans);
}
posted @ 2020-07-20 17:32  枫叶艾辰  阅读(99)  评论(0编辑  收藏  举报