LeetCode 400. Nth Digit

题目:

  • Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …

  • n is positive and will fit within the range of a 32-bit signed integer (n < 231).

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.

思路:

  • 第1步,求出对应的number应该是几位数——digit。
  • 第2步,求出该number在所有digit位数中排第几——quotient(从0开始),求出n对应位是该number的第几位——remainder(0代表最高位)。
  • 第3步,求出结果,如果是最高位,需要加1,因为最高位从1开始。

  • 注意:quotient/(int)Math.pow(10,digit-remainder-1)%10的写法我想了好久,毕竟数目只能是0~9,结尾应该有%10/(int)Math.pow(10,digit-remainder-1)是取出该位数字

代码:

public class Solution {
    public int findNthDigit(int n) {
        // find the digit and the position in current digit
        int digit = 1; // digit
        long base = 9; // the number of every digits:9,9*2*10,9*3*100
        while(n-base>0){
            n-=base;
            digit++;
            base=base/(digit-1)*digit*10;
        }

        // pos start from 0, than remainder==0 mains the highest digit when digit=1 or digit>1.
        // if pos start from 1, than remainder==0 mains the highest digit when digit=1.And remainder==1 mains the highest digit when digit>1 
        n--; 
        int quotient = n/digit; // which num
        int remainder = n%digit; // which digit of num

        if(remainder==0){
            return quotient/(int)Math.pow(10,digit-remainder-1)%10+1;// highest digit start from 1
        }else{
            return quotient/(int)Math.pow(10,digit-remainder-1)%10;// other digit start from 0
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值