【劍指 Offer 題解】44. 數字序列中的某一位數字

題目

數字以 0123456789101112131415… 的格式序列化到一個字符串中,求這個字符串的第 index 位。

思路

  • 一個數字一個數字遍歷,記錄當前數字在字符串的下標。
public int getDigitAtIndex(int index) {
	if(index < 0) {
		return -1;
	}
	int curIndex = 0;
	int curNum = 0;
	while (curIndex <= index) {
		curIndex += String.valueOf(curNum).length();
		curNum++;
	}
	String str = String.valueOf(curNum - 1);
	int i = str.length() - (curIndex - index);
	return str.charAt(i) - '0';
}

方法2

  • 如0-9一共佔10位,10-99一共佔180位…並進行累加,
  • 一旦累加的和超過給定的位數,可以找到目標數字的一個大概範圍
public int getDigitAtIndex(int index) {
    if (index < 0)
        return -1;
    int place = 1;  // 1 表示個位,2 表示 十位...
    while (true) {
        int amount = getAmountOfPlace(place);
        int totalAmount = amount * place;
        if (index < totalAmount)
            return getDigitAtIndex(index, place);
        index -= totalAmount;
        place++;
    }
}

/**
 * place 位數的數字組成的字符串長度
 * 10, 90, 900, ...
 */
private int getAmountOfPlace(int place) {
    if (place == 1)
        return 10;
    return (int) Math.pow(10, place - 1) * 9;
}

/**
 * place 位數的起始數字
 * 0, 10, 100, ...
 */
private int getBeginNumberOfPlace(int place) {
    if (place == 1)
        return 0;
    return (int) Math.pow(10, place - 1);
}

/**
 * 在 place 位數組成的字符串中,第 index 個數
 */
private int getDigitAtIndex(int index, int place) {
    int beginNumber = getBeginNumberOfPlace(place);
    int shiftNumber = index / place;
    String number = (beginNumber + shiftNumber) + "";
    int count = index % place;
    return number.charAt(count) - '0';
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章