试图更有效地解决这个问题
我读了一个自然数字,最多有9位数字。我必须形成一个以该数字的偶数数字的向量,每位数字一次出现一次(示例:987622222将输出:2 6 8)。我想知道我可以在此代码中添加哪些优化,以提高其效率。
#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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
示例输入/输出:
The
std::set
container is your friend, here. It automatically sorts its elements and only keeps one (unique) element for each value:Example input/output: