Nth character in Concatenated Decimal String | Java 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
class GFG { static char getDigit ( int N , int d ) { String str = Integer . toString ( N ) ; return str . charAt ( d - 1 ) ; } static 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 = ( int ) ( Math . ceil ( ( double ) ( N ) / ( double ) ( len ) ) ) ; int d = N % len ; if ( d == 0 ) d = len ; return getDigit ( dist + diff , d ) ; } public static void main ( String [ ] args ) { int N = 251 ; System . out . println ( getNthChar ( N ) ) ; } }