leetcode-7-Reverse-Integer

描述


Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

分析


把一个数字倒过来,题目不难,需要考虑的是边界情况,如果越界,返回0

解决方案1(python)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def reverse(self, x: int) -> int:
INT_MIN, INT_MAX = -2**31, 2**31-1

result = 0
while x != 0:
if result < INT_MIN // 10 + 1 or result > INT_MAX // 10:
return 0
nowDigit = x % 10
if x < 0 and nowDigit < 10:
nowDigit -= 10
x = (x - nowDigit) // 10
result = result * 10 + nowDigit
return result

解决方案2(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int reverse(int x) {
long long result = 0;

while(x != 0) {
int now = x % 10;
result = result * 10 + now;
if(result > INT_MAX || result < INT_MIN) {
return 0;
}
x = x / 10;
}
return result;
}
};

解决方案3(Rust)


1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pub fn reverse(x: i32) -> i32 {
x.signum() * x
.abs()
.to_string()
.chars()
.rev()
.collect::<String>()
.parse::<i32>()
.unwrap_or(0)
}
}

解决方案4(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
func reverse(x int) int {
result := 0
for x != 0 {
if result < math.MinInt32 / 10 || result > math.MaxInt32 / 10 {
return 0
}
nowDigit := x % 10
x /= 10
result = result * 10 + nowDigit
}
return result
}

相关问题


题目来源