7-整数反转

题目描述

题目链接:7. 整数反转 - 力扣(LeetCode) (leetcode-cn.com)

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

如果反转后整数超过 32 位的有符号整数的范围 $[−{2^{31}}, {2^{31}} − 1]$ ,就返回 0。

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

示例1:

1
2
输入:x = 123
输出:321

示例2:

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

示例3:

1
2
输入:x = 120
输出:21
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int reverse(int x) {
long res = 0;
while(x != 0){
// 取出x的末尾数字 x % 10
res = res * 10 + x % 10;
x /= 10;
}
return (int) res == res ? (int) res : 0;
}
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!