400. Nth Digit (找第n个数字)

た 入场券 2022-07-15 01:38 223阅读 0赞

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:

  1. Input:
  2. 3
  3. Output:
  4. 3

Example 2:

  1. Input:
  2. 11
  3. Output:
  4. 0
  5. Explanation:
  6. 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.
  7. public class Solution {
  8. public int findNthDigit(int n) {
  9. int len = 1;
  10. long num = 9, start = 0;
  11. while (n > num*len) {
  12. n -= len * num;
  13. start+=num;
  14. len++;
  15. num *= 10;
  16. }
  17. int res;
  18. if(n%len==0){
  19. res = (""+(start+n/len)).charAt(len-1)-'0';
  20. }else{
  21. res = (""+(start+n/len+1)).charAt(n%len-1)-'0';
  22. }
  23. return res;
  24. }
  25. }

发表评论

表情:
评论列表 (有 0 条评论,223人围观)

还没有评论,来说两句吧...

相关阅读