Skip to main content

Numbers containing 1,2 and 3

Task: Given an array of N numbers. Print only those numbers, which are consist of 1, 2 and 3.

Example:
Input:
1
4
1 2 3 4
Output:
1 2 3

Here is the Code:
Program in C++:

  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. bool isValid(int n)
  5. {
  6.     int a;
  7.     if(n==0) return 0;
  8.     while(n!=0)
  9.     {
  10.         a=n%10;
  11.         if(a==1||a==2||a==3) n/=10;
  12.         else return 0;
  13.     }
  14.     return 1;
  15. }
  16. int numbers(int *a,int n)
  17. {
  18.     map<int,int> m;
  19.     for(int i=0;i<n;i++)
  20.     {
  21.         if(isValid(a[i]))
  22.         {
  23.             m[a[i]]++;
  24.         }
  25.     }
  26.     int c=0;
  27.     for(auto i=m.begin();i!=m.end();i++)
  28.     {
  29.         while(i->second--) cout<<i->first<<" ";
  30.         c=1;
  31.     }
  32.     if(c==0) cout<<-1;
  33. }
  34. int main()
  35.  {
  36. int t;
  37. cin>>t;
  38. while(t--)
  39. {
  40.     int n;
  41.     cin>>n;
  42.     int a[n];
  43.     for(int i=0;i<n;i++)
  44.     {
  45.         cin>>a[i];
  46.     }
  47.     numbers(a,n);
  48.     cout<<endl;
  49. }
  50. return 0;
  51. }


Here is the Video: