Count numbers from 1 to n that have 4 as a digit | 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 code
function countNumbersWith4 ( n ) { let result = 0 ; for ( let x = 1 ; x <= n ; x ++ ) result += has4 ( x ) ? 1 : 0 ; return result ; } function has4 ( x ) { while ( x != 0 ) { if ( x % 10 == 4 ) return true ; x = Math . floor ( x / 10 ) ; } return false ; } let n = 328 ; document . write ( " " + n + " " + countNumbersWith4 ( n ) ) ;