Reputation: 1
I read a natural number with at most 9 digits. I have to form a vector with the even digits of that number, in ascending order, with each digit appearing once (example : 98762222 is going to output: 2 6 8). I want to know what optimisations can I add to this code to make it more efficient.
#include <iostream>
using namespace std;
int main()
{ int x,i,k=0,copy,v[10]={0},j;
cout<<"x=";
cin>>x;
copy=x;
if (x==0)
cout<<0;
while (x>0)
{
v[x%10]++;
x/=10;
}
for (i=0; i<10; i=i+2)
{
if(v[i]>0)
{
k++;
}
}
int w[k]={0};
if (k>0)
{ j=0;
for (i=0; i<10; i=i+2)
if(v[i]>0)
{ w[j]=i;
j++;}
}
for (j=0; j<k; j++)
cout<<w[j]<<" ";
if (k==0 && copy!=0)
cout<<"No even digits";
return 0;
}
Upvotes: 0
Views: 71
Reputation: 51825
The std::set
container is your friend, here. It automatically sorts its elements and only keeps one (unique) element for each value:
#include <iostream>
#include <set>
int main()
{
int64_t x; // You should use int64_t to cover ALL 9-digit numbers
std::cout << "x=";
std::cin >> x;
std::set<int> s; // But each digit will be OK as a plain "int"
while (x > 0)
{
int digit = x % 10;
if (digit % 2 == 0) s.insert(digit);
x /= 10;
}
if (s.size() == 0) std::cout << "No even digits.";
else for (auto d : s) std::cout << d << " ";
std::cout << "\n";
return 0;
}
Example input/output:
x=98762222
2 6 8
Upvotes: 2