问题

剑指 Offer 44. 数字序列中某一位的数字
难度中等51
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
示例 1:
输入:n = 3
输出:3
示例 2:
输入:n = 11
输出:0
限制:

  • 0 <= n < 2^31

解答

  1. class Solution {
  2. public int findNthDigit(int n) {
  3. int digit = 1;
  4. long start = 1; // long 防止 int 类型溢出
  5. long count = 9;
  6. //
  7. while(n > count){
  8. n -= count;
  9. start *= 10;
  10. digit += 1;
  11. count = 9 * digit * start;
  12. }
  13. long num = start + (n-1) / digit; // 把 start 所在的位置下标为0, n所在的位置就要 n-1
  14. int index = (n-1) % digit;
  15. String s = String.valueOf(num);
  16. return s.charAt(index) - '0';
  17. }
  18. }

大佬的解答:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/solution/mian-shi-ti-44-shu-zi-xu-lie-zhong-mou-yi-wei-de-6/