Number of occurrences of 2 as a digit in numbers from 0 to n | Java program to count 2 s 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
class GFG { static int number0f2s ( int n ) { int count = 0 ; while ( n > 0 ) { if ( n % 10 == 2 ) count ++ ; n = n / 10 ; } return count ; } static int numberOf2sinRange ( int n ) { int count = 0 ; for ( int i = 2 ; i <= n ; i ++ ) count += number0f2s ( i ) ; return count ; } public static void main ( String [ ] args ) { System . out . print ( numberOf2sinRange ( 22 ) ) ; System . out . println ( ) ; System . out . print ( numberOf2sinRange ( 100 ) ) ; } }