From aa48a1ba631846f3452f2f68fc05be6e6d911de5 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 18 Sep 2016 22:45:05 +0800 Subject: [PATCH] Create nth-digit.cpp --- C++/nth-digit.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 C++/nth-digit.cpp diff --git a/C++/nth-digit.cpp b/C++/nth-digit.cpp new file mode 100644 index 000000000..c30adbf0b --- /dev/null +++ b/C++/nth-digit.cpp @@ -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; + } +};