44. 数字序列中的某一位数字

题目描述

数字以 0123456789101112131415… 的格式序列化到一个字符串中,求这个字符串的第 index 位。

解题思路

  1. public int getDigitAtIndex(int index) {
  2. if (index < 0)
  3. return -1;
  4. int place = 1; // 1 表示个位,2 表示 十位...
  5. while (true) {
  6. int amount = getAmountOfPlace(place);
  7. int totalAmount = amount * place;
  8. if (index < totalAmount)
  9. return getDigitAtIndex(index, place);
  10. index -= totalAmount;
  11. place++;
  12. }
  13. }
  14. /**
  15. * place 位数的数字组成的字符串长度
  16. * 10, 90, 900, ...
  17. */
  18. private int getAmountOfPlace(int place) {
  19. if (place == 1)
  20. return 10;
  21. return (int) Math.pow(10, place - 1) * 9;
  22. }
  23. /**
  24. * place 位数的起始数字
  25. * 0, 10, 100, ...
  26. */
  27. private int getBeginNumberOfPlace(int place) {
  28. if (place == 1)
  29. return 0;
  30. return (int) Math.pow(10, place - 1);
  31. }
  32. /**
  33. * 在 place 位数组成的字符串中,第 index 个数
  34. */
  35. private int getDigitAtIndex(int index, int place) {
  36. int beginNumber = getBeginNumberOfPlace(place);
  37. int shiftNumber = index / place;
  38. String number = (beginNumber + shiftNumber) + "";
  39. int count = index % place;
  40. return number.charAt(count) - '0';
  41. }

44. 数字序列中的某一位数字 - 图1