Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
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位带符号的数字,将这个数字方向
题目很简单,就直接上代码了,
fun reverse(x: Int): Int {
var x = x
var result = 0
while (x != 0) {
val num = x % 10
val lastResult = result
result = result * 10 + num
if (result / 10 - lastResult != 0) {
return 0
}
x /= 10
}
return result
}
简单说下思路:
循环拆解X的个位数,然后将拆解下面的个位数拼接到返回结果的result的上,需要注意的是先将result的原始数进一位,直到X拆解为0为止。