Count total number of digits from 1 to n | PHP program to count total number of digits we have to write from 1 to n ; number_of_digits store total digits we have to write ; In the loop we are decreasing 0 , 9 , 99 ... from n till ( n - i + 1 ) is greater than 0 and sum them to number_of_digits to get the required sum ; Driver Code
< ? php function totalDigits ( $ n ) { $ number_of_digits = 0 ; for ( $ i = 1 ; $ i <= $ n ; $ i *= 10 ) $ number_of_digits += ( $ n - $ i + 1 ) ; return $ number_of_digits ; } $ n = 13 ; echo totalDigits ( $ n ) ; ? >