Number of occurrences of 2 as a digit in numbers from 0 to n | Counts the number of 2 s in a number at d - th digit ; if the digit in spot digit is ; Counts the number of '2' digits between 0 and n ; Convert integer to String to find its length ; Traverse every digit and count for every digit ; Driver Code
function count2sinRangeAtDigit ( number , d ) { var powerOf10 = parseInt ( Math . pow ( 10 , d ) ) ; var nextPowerOf10 = powerOf10 * 10 ; var right = number % powerOf10 ; var roundDown = number - number % nextPowerOf10 ; var roundup = roundDown + nextPowerOf10 ; var digit = parseInt ( number / powerOf10 ) % 10 ; if ( digit < 2 ) { return roundDown / 10 ; } if ( digit == 2 ) { return roundDown / 10 + right + 1 ; } return roundup / 10 ; } function numberOf2sinRange ( number ) { var convert ; convert = number . toString ( ) ; var s = convert ; var len = s . length ; var count = 0 ; for ( digit = 0 ; digit < len ; digit ++ ) { count += count2sinRangeAtDigit ( number , digit ) ; } return count ; } document . write ( numberOf2sinRange ( 22 ) ) ; document . write ( " " + numberOf2sinRange ( 100 ) ) ;