- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Finding nth digit of natural numbers sequence in JavaScript
- Find nth number that contains the digit k or divisible by k in C++
- Finding the nth digit of natural numbers JavaScript
- Nth Magical Number in C++
- Find nth Hermite number in C++
- Count n digit numbers not having a particular digit in C++
- Count ‘d’ digit positive integers with 0 as a digit in C++
- C/C++ Program for nth Catalan Number?
- 3-digit Osiris number in C?
- Number of Digit One in C++
- Program to find nth ugly number in C++
- C Program for nth Catalan Number
- Find Nth term (A matrix exponentiation example) in C++
- Program to find Nth Even Fibonacci Number in C++
- Delete nth element from headnode using C#

Advertisements