Nth character in Concatenated Decimal String | C ++ program to get Nth character in concatenated Decimal String ; Utility method to get dth digit of number N ; Method to return Nth character in concatenated decimal string ; sum will store character escaped till now ; dist will store numbers escaped till now ; loop for number lengths ; nine * len will be incremented characters and nine will be incremented numbers ; restore variables to previous correct state ; get distance from last one digit less maximum number ; d will store dth digit of current number ; method will return dth numbered digit of ( dist + diff ) number ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; char getDigit ( int N , int d ) { string str ; stringstream ss ; ss << N ; ss >> str ; return str [ d - 1 ] ; } char getNthChar ( int N ) { int sum = 0 , nine = 9 ; int dist = 0 , len ; for ( len = 1 ; ; len ++ ) { sum += nine * len ; dist += nine ; if ( sum >= N ) { sum -= nine * len ; dist -= nine ; N -= sum ; break ; } nine *= 10 ; } int diff = ceil ( ( double ) N / len ) ; int d = N % len ; if ( d == 0 ) d = len ; return getDigit ( dist + diff , d ) ; } int main ( ) { int N = 251 ; cout << getNthChar ( N ) << endl ; return 0 ; }