用C++编写函数将一个整数首尾倒置
时间: 2024-10-25 11:08:52 浏览: 35
在C++中,你可以通过一些简单的步骤来编写一个函数,用于将一个整数的数字顺序反转。这个过程通常涉及到将数字转换为字符串,然后反转字符串再转换回整数。下面是一个简单的实现示例:
```cpp
#include <string>
#include <sstream>
int reverseInteger(int num) {
// 将整数转换为字符串
std::ostringstream oss;
oss << num;
// 反转字符串
std::string reversedStr = oss.str();
std::reverse(reversedStr.begin(), reversedStr.end());
// 再次转换回整数
int reversedNum;
if (std::istringstream(oss.str()) >> reversedNum) {
return reversedNum; // 如果转换成功,返回反转后的整数
} else {
throw std::invalid_argument("Invalid number cannot be reversed.");
}
}
// 使用示例
int main() {
int input = 123456;
try {
int reversed = reverseInteger(input);
std::cout << "Reversed integer: " << reversed << std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)