Compute sum of digits in all numbers from 1 to n | Returns sum of all digits in numbers from 1 to n ; initialize result ; One by one compute sum of digits in every number from 1 to n ; A utility function to compute sum of digits in a given number x ; Driver Program
function sumOfDigitsFrom1ToN ( n ) { let result = 0 ; for ( let x = 1 ; x <= n ; x ++ ) result += sumOfDigits ( x ) ; return result ; } function sumOfDigits ( x ) { let sum = 0 ; while ( x != 0 ) { sum += x % 10 ; x = parseInt ( x / 10 , 10 ) ; } return sum ; } let n = 328 ; document . write ( " " + " " + n + " " + sumOfDigitsFrom1ToN ( n ) ) ;