問題
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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
分析:
將數字翻轉,如果超過32-bit就返回0.
照常翻轉就可以,定義的res爲int 32-bit,如果翻轉後超出範圍,那必然每一位會發生很大的變化。根據這個特性可以在迭代生成output時檢查是否有突變,若突變則返回0.
java
class Solution {
public int reverse(int x) {
int res = 0, privious = 0;
while(x != 0){
privious = res;
res = res * 10 + (x%10);
if(res/10 != privious) return 0; //檢查突變
x /= 10;
}
return res;
}
}