【leetcode】7. Reverse Integer
阿新 • • 發佈:2018-12-12
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.
while (x != 0) {
res = res * 10 + x % 10;
x /= 10;
}
是翻轉整數的方法,同樣適用於負數,不受影響,但是要考慮到過程中res越界的問題,所以加入if (Math.abs(res) > Integer.MAX_VALUE/10) return 0;提前考慮是否大於max的10分之1
while (x != 0) { if (Math.abs(res) > Integer.MAX_VALUE/10) return 0; res = res * 10 + x % 10; x /= 10; }
也考慮一下這種寫法,但是如果題目啊直接要求就是long long 型別的話就處理不了了
class Solution {
public:
int reverse(int x) {
long long res = 0;
while (x != 0) {
res = 10 * res + x % 10;
x /= 10;
}
return (res > INT_MAX || res < INT_MIN) ? 0 : res;
}
};