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
def count2sinRangeAtDigit ( number , d ) : NEW_LINE INDENT powerOf10 = int ( pow ( 10 , d ) ) ; NEW_LINE nextPowerOf10 = powerOf10 * 10 ; NEW_LINE right = number % powerOf10 ; NEW_LINE roundDown = number - number % nextPowerOf10 ; NEW_LINE roundup = roundDown + nextPowerOf10 ; NEW_LINE digit = ( number // powerOf10 ) % 10 ; NEW_LINE if ( digit < 2 ) : NEW_LINE INDENT return roundDown // 10 ; NEW_LINE DEDENT if ( digit == 2 ) : NEW_LINE INDENT return roundDown // 10 + right + 1 ; NEW_LINE DEDENT return roundup // 10 ; NEW_LINE DEDENT def numberOf2sinRange ( number ) : NEW_LINE INDENT s = str ( number ) ; NEW_LINE len1 = len ( s ) ; NEW_LINE count = 0 ; NEW_LINE for digit in range ( len1 ) : NEW_LINE INDENT count += count2sinRangeAtDigit ( number , digit ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT print ( numberOf2sinRange ( 22 ) ) ; NEW_LINE print ( numberOf2sinRange ( 100 ) ) ; NEW_LINE