[编程题]提取不重复的整数

来源:互联网 发布:软件工程和软件危机 编辑:程序博客网 时间:2024/06/05 03:35

Talk is cheap, show me the code.

一、问题描述

输入一个int型整数,按照从右向左的阅读顺序,返回一个不含重复数字的新的整数。

输入描述:

输入一个int型整数

输出描述:

按照从右向左的阅读顺序,返回一个不含重复数字的新的整数

输入例子:

9876673

输出例子:

37689

二、问题分析

读一个数字,可以保存为int或者string,这里因为要保证数字的顺序,而不是按大小排序,所以不能用set,那么只能用10个bool值的数组来记录一个数字是否已经访问过,最终的结果也可以用一个字符串或者int来保存,再输出。

解决方式1:

采用string保存输入,string保存输出。

#include <iostream>#include <string>using namespace std;int main(){    string s;    while (cin >> s)    {        string str;        bool ch[10];        for (int i = 0; i < 10; i++)        {            ch[i] = true;        }        for (string::reverse_iterator it = s.rbegin(); it != s.rend(); ++it)        {            if(!ch[*it - '0'])            {                continue;            } else {                ch[*it - '0'] = false;                str += (*it);            }        }        cout << str << endl;    }    return 0;}

解决方式2:

采用int保存输入,string保存输出,注意数字转字符串不能用 数字+”” 的形式,这样得到的是ASCII码空字符后数字位的字符,正确数字转字符串是采用 数字+‘0’ 的形式,先得到数字的字符形式,然后在自动转换成字符串。

#include <iostream>#include <string>using namespace std;int main(){    int a;    while (cin >> a)    {        string str = "";        bool ch[10] = {0};        while (a >= 1)        {            int temp = a % 10;            a /= 10;            if (ch[temp])            {                continue;            } else {                ch[temp] = true;                str += (temp + '0');            }        }        cout << str << endl;    }    return 0;}

解决方式3:

采用int保存输入,int保存输出。

#include<iostream>using namespace std;int main(){    int n;    int a[10]={0};    int num=0;    cin>>n ;    while(n)    {        if(a[n%10]==0)        {            a[n%10]++;            num=num*10+n%10;        }        n/=10;    }        cout<<num<<endl;        return 0;}
0 0
原创粉丝点击