Nth character in Concatenated Decimal String | 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
< ? php function getDigit ( $ N , $ d ) { $ string = strval ( $ N ) ; return $ string [ $ d - 1 ] ; } function getNthChar ( $ N ) { $ sum = 0 ; $ nine = 9 ; $ dist = 0 ; for ( $ len = 1 ; $ len < $ N ; $ len ++ ) { $ sum += $ nine * $ len ; $ dist += $ nine ; if ( $ sum >= $ N ) { $ sum -= $ nine * $ len ; $ dist -= $ nine ; $ N -= $ sum ; break ; } $ nine *= 10 ; } $ diff = ( $ N / $ len ) + 1 ; $ d = $ N % $ len ; if ( $ d == 0 ) $ d = $ len ; return getDigit ( $ dist + $ diff , $ d ) ; } $ N = 251 ; echo getNthChar ( $ N ) ; ? >