Number of occurrences of 2 as a digit in numbers from 0 to n | Java code for above implementation ; Driver code
class GFG { static int numberOf2sinRange ( int n ) { String s = " " ; for ( int i = 0 ; i < n + 1 ; i ++ ) s += String . valueOf ( i ) ; int count = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) == '2' ) { count ++ ; } } return count ; } public static void main ( String [ ] args ) { int n = 30 ; System . out . println ( numberOf2sinRange ( n ) ) ; } }