Find the n
th digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
n
?
n
is a positive integer and can be very large, within the range [1, 2^31 - 1]
.n
th digit will always be a single digit from 0 to 9.d
digits contribute d * 9 * (10^(d-1))
digits.n
th digit falls.#include <iostream>
#include <cmath>
class Solution {
public:
int findNthDigit(int n) {
long long len = 1; // number of digits in the current number range
long long count = 9;
long long start = 1;
// Determine the range where the nth digit is
while (n > len * count) {
n -= len * count;
len++;
count *= 10;
start *= 10;
}
// Find the exact number and the digit position
start += (n - 1) / len;
std::string num = std::to_string(start);
return num[(n - 1) % len] - '0'; // Access the exact digit and convert to integer
}
};
int main() {
Solution solution;
int n = 400;
std::cout << solution.findNthDigit(n) << std::endl; // Output for the given example
return 0;
}
O(log n)
O(1)
n
. The space used for conversion to a string and accessing a character is also constant.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?