
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Nth Digit in C++
Suppose we have one infinite integer sequence, we have to find the nth digit of this sequence. So if the input is 11, then the output will be 0 as if we place the numbers like 123456789101112, so the 11th digit is 0.
To solve this, we will follow these steps −
len := 0 and cnt := 9 and start := 1
-
while n > len * cnt
n := n – (len * cnt)
cnt := cnt * 10, start := start * 10
increase len by 1
start := start +(n - 1) / len
s := start as string
return s[(n – 1) mod len]
Example (C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; typedef long long int lli; class Solution { public: int findNthDigit(int n) { lli len = 1; lli cnt = 9; lli start = 1; while(n > len * cnt){ n -= len * cnt; cnt *= 10; start *= 10; len++; } start += (n - 1) / len; string s = to_string(start); return s[(n - 1) % len] - '0'; } }; main(){ Solution ob; cout << (ob.findNthDigit(11)); }
Input
11
Output
0
Advertisements