找到与给定数字绝对值最小的回文数,cpp代码
时间: 2024-05-08 18:19:11 浏览: 17
Sure, here's the C++ code to find the palindrome number with the smallest absolute difference from a given number:
```C++
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
int ans = INT_MAX;
string best = "";
for (int i = 0; i <= 9999; ++i) {
string s = to_string(i);
string rev = s;
reverse(rev.begin(), rev.end());
s += rev;
int num = stoi(s);
int diff = abs(num - n);
if (diff < ans) {
ans = diff;
best = s;
}
}
cout << best << endl;
return 0;
}
```
This program generates all possible palindromes up to four digits, computes the absolute difference from the given number, and keeps track of the smallest difference found so far. Once all palindromes are generated, the program outputs the one with the smallest difference. Note that this program assumes that the given number is non-negative.
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)