c++数字的反转给定一个整数,请将该数各个位上数字反转得到一个新数。新数也应满足整数的常见形式,即除非给定的原数为零,否则反转后得到的新数的最高位数字不应为零(实现
时间: 2025-03-09 22:14:03 浏览: 91
### C++ 实现整数反转
为了实现不含前导零的整数反转功能,在C++中可以通过以下方法完成:
```cpp
#include <iostream>
#include <cmath>
class Solution {
public:
static int reverseInteger(int x) {
long result = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
// Check for overflow and underflow conditions.
if (result > INT_MAX / 10 || (result == INT_MAX / 10 && pop > 7)) return 0;
if (result < INT_MIN / 10 || (result == INT_MIN / 10 && pop < -8)) return 0;
result = result * 10 + pop;
}
// Remove leading zeros by converting to string then back to integer.
std::stringstream ss;
ss << std::abs(result);
std::string strResult = ss.str();
strResult.erase(0, strResult.find_first_not_of('0')); // Erase leading '0's.
int finalResult = 0;
if (!strResult.empty()) {
ss.clear();
ss.str(strResult);
ss >> finalResult;
// Restore the sign of original number.
if (result < 0) finalResult *= -1;
}
return finalResult;
}
};
// Example usage
int main() {
int num = 123456000; // Test case with trailing zeros.
std::cout << "Reversed Integer: " << Solution::reverseInteger(num) << "\n";
num = -987654321; // Negative test case.
std::cout << "Reversed Integer: " << Solution::reverseInteger(num) << "\n";
return 0;
}
```
此代码片段展示了如何安全地处理溢出情况以及去除反转后的任何前导零。注意这里使用了`std::stringstream`来辅助去掉前导零并保持符号一致。
阅读全文
相关推荐














