Number of occurrences of 2 as a digit in numbers from 0 to n | Counts the number of '2' digits in a single number ; Counts the number of '2' digits between 0 and n ; Initialize result ; Count 2 's in every number  from 2 to n ; Driver code
function number0f2s ( n ) { let count = 0 ; while ( n > 0 ) { if ( n % 10 == 2 ) count ++ ; n = parseInt ( n / 10 , 10 ) ; } return count ; } function numberOf2sinRange ( n ) { let count = 0 ; for ( let i = 2 ; i <= n ; i ++ ) count += number0f2s ( i ) ; return count ; } document . write ( numberOf2sinRange ( 22 ) + " " ) ; document . write ( numberOf2sinRange ( 100 ) ) ;