JAVA leetcode&剑指offer 面试题44. 数字序列中某一位的数字 我的解题记录

题目
在这里插入图片描述

解题思路

首先,我们要明确的是,n是下标,从0开始的!
我们可以注意到规律 0到9有10个数字,10到99有90个数字,100到999有900个数字,so~

代码

class Solution {
    public int findNthDigit(int n) {
        if (n<10)
            return n;
        int i = 1;
        while (n>i*(Math.pow(10,i-1))*9){   //循环结束后,i-1就是位数,n-1为表示还要找多少个
            n -= i*Math.pow(10,i-1)*9;
            i++;
        }
        char[] result = String.valueOf((int) Math.pow(10,i-1) + (n-1) / i).toCharArray();//我们用字符串来接收值,方便找位数 result结果为我们要的那个数的
        int value = result[(n-1)%i]-'0';    //(n-1)%位数 得出我们要的第x位的数
        return value;
    }
}
原创文章 14 获赞 52 访问量 1495

猜你喜欢

转载自blog.csdn.net/weixin_44233929/article/details/105546436