Number of occurrences of 2 as a digit in numbers from 0 to n | Javascript code for above implementation ; Driver code
function numberOf2sinRange ( n ) { var s = " " ; for ( var i = 0 ; i < n + 1 ; i ++ ) s += i . toString ( ) ; var count = 0 ; for ( var i = 0 ; i < s . length ; i ++ ) { if ( s . charAt ( i ) == ' ' ) { count ++ ; } } return count ; } var n = 30 ; document . write ( numberOf2sinRange ( n ) ) ;