剑指offer_数字序列中的某一位数字
题目描述
数字以 0123456789101112131415... 的格式序列化到一个字符串中,求这个字符串的第 index 位。
1 public class Solution { 2 3 public int getDigitAtIndex(int index) { 4 if (index < 0) 5 return -1; 6 int place = 1; // 1 表示个位,2 表示 十位... 7 while (true) { 8 int amount = getAmountOfPlace(place); 9 int totalAmount = amount * place; 10 if (index < totalAmount) 11 return getDigitAtIndex(index, place); 12 index -= totalAmount; 13 place++; 14 } 15 } 16 17 /** 18 * place 位数的数字组成的字符串长度 10, 90, 900, ... 19 */ 20 private int getAmountOfPlace(int place) { 21 if (place == 1) 22 return 10; 23 return (int) Math.pow(10, place - 1) * 9; 24 } 25 26 /** 27 * place 位数的起始数字 0, 10, 100, ... 28 */ 29 private int getBeginNumberOfPlace(int place) { 30 if (place == 1) 31 return 0; 32 return (int) Math.pow(10, place - 1); 33 } 34 35 /** 36 * 在 place 位数组成的字符串中,第 index 个数 37 */ 38 private int getDigitAtIndex(int index, int place) { 39 int beginNumber = getBeginNumberOfPlace(place); 40 int shiftNumber = index / place; 41 String number = (beginNumber + shiftNumber) + ""; 42 int count = index % place; 43 return number.charAt(count) - '0'; 44 } 45 }

浙公网安备 33010602011771号