for (int bit = 1; bit <= 11; bit++) { long firstNum = pow(10, bit - 1); long lastNum = pow(10, bit) - 1; long bitNums = lastNum - firstNum + 1; long totalNums = bitNums * bit; // cout << "firstNum: " << firstNum // << ", lastNum: " << lastNum // << ", bitNums: " << bitNums // << ", totalNums: " << totalNums << endl; if (n < totalNums) { int numTimes = n / bit; int numIndex = n % bit; int targetNum = firstNum + numTimes; string targetStr = to_string(targetNum); // cout << "n: " << n // << ", numTimes: " << numTimes // << ", numIndex: " << numIndex // << ", targetNum: " << targetNum << endl; return targetStr[numIndex] - '0'; } n -= totalNums; }
return-1; }
// leetcode 400. 解法 intfindKthNumberCore2(int n){ int digit = 1; // 数位(个位, 十位2, 百位3, ...) long base = 1; // 该数位的起始数(1, 10, 100, 1000, ...) long index_cnt = 9 * base * digit; // 该数位的索引个数(不是数字个数)
while (index_cnt < n) { n -= index_cnt; base *= 10; digit ++; index_cnt = 9 * base * digit; // cout << "n: " << n // << ", base: " << base // << ", digit: " << digit // << ", index_cnt: " << index_cnt << endl; }
// 假设 base = 1000,说明 n 是 100~999 中某个三位数的某一位 // 这个数,这样算: long val = base + (n - 1) / digit; // 这个数的第几位,这样算: int index = (n - 1) % digit; cout << "val: " << val << ", index: " << index << endl;
// val 第 index 位数字 string valStr = to_string(val); return valStr[index] - '0'; } };