mobile wallpaper 1
mobile wallpaper 2
mobile wallpaper 3
mobile wallpaper 4
127 字
1 分钟
LeetCode 面试经典150题 [22.5/150 整数反转]
2024-06-21
2024-06-23

至于为什么是22.5,因为做错了,这道不在面试经典题里

题目描述#

给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。

如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。

假设环境不允许存储 64 位整数(有符号或无符号)。

示例 1:

输入:x = 123
输出:321

示例 2:

输入:x = -123
输出:-321

示例 3:

输入:x = 120
输出:21

示例 4:

输入:x = 0
输出:0

个人C++解答#

class Solution {
public:
int reverse(int x) {
string str = to_string(x);
string result = "";
if (x>=0) {
for (int i = str.length() - 1; i >= 0; i--) {
result.push_back(str[i]);
}
}
else {
result.push_back('-');
for (int i = str.length() - 1; i > 0; i--) {
result.push_back(str[i]);
}
}
long int num = stoll(result);
if (num<INT_MIN || num>INT_MAX) { return 0; }else{
return (int)num;
}
}
};
分享

如果这篇文章对你有帮助,欢迎分享给更多人!

LeetCode 面试经典150题 [22.5/150 整数反转]
https://ericonline.cn/posts/leetcode-面试经典150题-23-150-整数反转/
作者
Eric
发布于
2024-06-21
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

目录