Number of occurrences of 2 as a digit in numbers from 0 to n | Write C ++ code here ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOf2sinRange ( int n ) { string s = " " ; for ( int i = 0 ; i < n + 1 ; i ++ ) s += to_string ( i ) ; int count = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == '2' ) { count ++ ; } } return count ; } int main ( ) { int n = 30 ; cout << numberOf2sinRange ( n ) ; return 0 ; }