先获得比当前数小的最近对称数,再获得比当前数大的最近对称数
在比较这两个对称数哪个最近,同样近则输出两个。
代码如下:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int strToInt(string str)
{
int ret = 0;
int j = 1;
for (int i = str.size()-1; i>=0; i--)
{
ret += (str[i]-48)*j;
j *= 10;
}
return ret;
}
//获取整形的基数
int getBase(int val)
{
int radix = 1;
int base = 1;
while (val / (radix *= 10) )
{
++base;
}
return base;
}
string intToStr(int val)
{
string str;
int base = getBase(val);
int radix = 1;
for (int i = 1; i< base; ++i)
{
radix *= 10;
}
for (int i = 1; i<= base; ++i)
{
str.push_back(val/radix%10 + 48);
radix /= 10;
}
return str;
}
// 判断是否为对称数
int isDuichenshu(string str)
{
for (int i = 0, j = str.size() -1; i < j; ++i, --j)
{
if (str[i] != str[j])
return 0;
}
return 1;
}
vector<string> getDuichenshu(string str)
{
string smallstr, bigstr;
vector<string> vec;
int num = strToInt(str);
while(--num)
{
string s2 = intToStr(num);
if (isDuichenshu(s2))
{
smallstr = s2;
break;
}
}
while (++num)
{
string s2 = intToStr(num);
if (isDuichenshu(s2))
{
bigstr = s2;
break;
}
}
//cout << smallstr << "," << bigstr << endl;
//取距离最近的对称数
if (strToInt(str) - strToInt(smallstr) < strToInt(bigstr) - strToInt(str))
vec.push_back(smallstr);
else if (strToInt(str) - strToInt(smallstr) > strToInt(bigstr) - strToInt(str))
vec.push_back(bigstr);
else
{
vec.push_back(smallstr);
vec.push_back(bigstr);
}
return vec;
}
int main()
{
string str = "126";
vector<string> vec;
vector<string>::iterator it;
vec = getDuichenshu(str);
cout << "126的最近对称数是:" << endl;
for (it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.end() - 1)
cout << *it << ", ";
else
cout << *it << endl;
}
str = "125";
vec = getDuichenshu(str);
cout << "125的最近对称数是:" << endl;
for (it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.end() - 1)
cout << *it << ", ";
else
cout << *it << endl;
}
str = "127";
vec = getDuichenshu(str);
cout << "127的最近对称数是:" << endl;
for (it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.end() - 1)
cout << *it << ", ";
else
cout << *it << endl;
}
return 0;
}
程序输出:
126的最近对称数是: 121, 131 125的最近对称数是: 121 127的最近对称数是: 131 
获取一个整数的最近对称数:等您坐沙发呢!