Skip to content

Commit

Permalink
Create nth-digit.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Sep 18, 2016
1 parent 888449e commit aa48a1b
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions C++/nth-digit.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Time: O(logn)
// Space: O(1)

class Solution {
public:
int findNthDigit(int n) {
int digit_len = 1;
while (n > digit_len * 9 * pow(10, digit_len - 1)) {
n -= digit_len * 9 * pow(10, digit_len - 1);
++digit_len;
}

const int num = pow(10, digit_len - 1) + (n - 1) / digit_len;

int nth_digit = num / pow(10, (digit_len - 1) - (n - 1) % digit_len);
nth_digit %= 10;

return nth_digit;
}
};

0 comments on commit aa48a1b

Please sign in to comment.