【LeetCode】7.Reverse Integer

1.题目描述

Given a 32-bit signed integer, reverse digits of an integer.

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

Example 1:

1
2
Input: 123
Output: 321

Example 2:

1
2
Input: -123
Output: -321

Example 3:

1
2
Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

2.Solutions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
object Solution {
def reverse(x: Int): Int = {
if(!isValidInteger(x))
return 0

if(x < 0)
return -reverseUtil(-x)

return reverseUtil(x)
}

def reverseUtil(x: Int): Int = {
var result: Long = 0
var vx = x
//类似于9. Palindrome Number
while (vx != 0) {
result = result * 10 + vx % 10
if(!isValidInteger(result))
return 0
vx /= 10
}

result.toInt
}

// Check if x is a valid integer.
def isValidInteger(x: Long): Boolean = {
if(x > Int.MaxValue || x < Int.MinValue)
return false
true
}
}
(完)
谢谢你请我吃糖果!
0%