Smallest number greater than or equal to N using only digits 1 to K | C ++ Program to find the smallest number greater than or equal to N which is made up of first K digits ; Function to count the digits greater than K ; Function to print the list ; Function to find the number greater than or equal to n , which is only made of first k digits ; If the number itself satisfy the conditions ; Check digit from back ; If digit > K is present previously and current digit is less than K ; If current digit is greater than K ; If an extra digit needs to be added ; Print the number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountGreater ( int n , int k ) { int a = 0 ; while ( n ) { if ( ( n % 10 ) > k ) { a ++ ; } n = n / 10 ; } return a ; } int PrintList ( list < int > ans ) { for ( auto it = ans . begin ( ) ; it != ans . end ( ) ; it ++ ) cout << * it ; } void getNumber ( int n , int k ) { int count = CountGreater ( n , k ) ; if ( count == 0 ) { cout << n ; return ; } list < int > ans ; bool changed = false ; while ( n > 0 ) { int digit = n % 10 ; if ( changed == true ) { ans . push_front ( digit ) ; } else { if ( count == 0 && digit < k ) { ans . push_front ( digit + 1 ) ; changed = true ; } else { ans . push_front ( 1 ) ; if ( digit > k ) { count -- ; } } } n = n / 10 ; } if ( changed == false ) { ans . push_front ( 1 ) ; } PrintList ( ans ) ; return ; } int main ( ) { int N = 51234 ; int K = 4 ; getNumber ( N , K ) ; return 0 ; }