take a number from stack and add a digit smaller than last digit of it .
while ( ! s . empty ( ) ) { int tp = s . top ( ) ; s . pop ( ) ; for ( int j = tp % 10 ; j <= 9 ; j ++ ) { int x = tp * 10 + j ; if ( x <= n ) { s . push ( x ) ; result ++ ; } } } } return result ; }