Count total number of digits from 1 to n | Javascript 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
function totalDigits ( n ) { var number_of_digits = 0 ; for ( var i = 1 ; i <= n ; i *= 10 ) number_of_digits += ( n - i + 1 ) ; return number_of_digits ; } var n = 13 ; document . write ( totalDigits ( n ) ) ;