Welcome to Subscribe On Youtube
Question
Formatted question description: https://leetcode.ca/all/7.html
Given a signed 32-bit integer x
, return x
with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range [-231, 231 - 1]
, then return 0
.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123 Output: 321
Example 2:
Input: x = -123 Output: -321
Example 3:
Input: x = 120 Output: 21
Constraints:
-231 <= x <= 231 - 1
Algorithm
One thing to pay attention to when flipping numbers is the overflow problem. After reading many online solutions, since the previous OJ did not test for overflow, many people’s solutions on the internet can pass OJ without dealing with the overflow problem.
Now OJ has updated the overflow test, so it still needs to be considered.
Why is there an overflow problem?
Since the value range of the int
type is -2147483648~2147483647
, if you want to flip the number within the range of 1000000009
to get 9000000001
, the number after the flip exceeds the range.
The initial idea is to use long
data, the value range of which is -9223372036854775808~9223372036854775807
, which is much larger than int
so that there will be no overflow problem.
Code
-
public class Reverse_Integer { public static void main(String[] args) { Reverse_Integer out = new Reverse_Integer(); Solution s = out.new Solution(); System.out.println(s.reverse(1234567899)); System.out.println(1234567899 * 10); // output: -539222898 } /* from online: If overflow exists, the new result will not equal previous one. No flags needed. No hard code like 0xf7777777 needed. */ public class Solution { public int reverse(int x) { int result = 0; while (x != 0) { int tail = x % 10; int newResult = result * 10 + tail; // If overflow exists, the new result will not equal previous one. /* result = 998765432 newResult = 1397719729 // here the program will do a cast, meaning overflow */ if ((newResult - tail) / 10 != result) { return 0; } result = newResult; x = x / 10; } return result; } } public class Solution_longType { public int reverse(int x) { int flag = 1; if (x < 0) { x *= -1; flag = -1; } long result = 0; // initialize as long type while(x > 0) { int least = x % 10; result = result * 10 + least; x /= 10; } // check overflow if(result > Integer.MAX_VALUE || result * flag < Integer.MIN_VALUE) { return 0; } return (int) (flag * result); } } } ############ class Solution { public int reverse(int x) { long res = 0; // 考虑负数情况,所以这里条件为: x != 0 while (x != 0) { res = res * 10 + (x % 10); x /= 10; } return res < Integer.MIN_VALUE || res > Integer.MAX_VALUE ? 0 : (int) res; } }
-
// OJ: https://leetcode.com/problems/reverse-integer/ // Time: O(1) // Space: O(1) class Solution { public: int reverse(int x) { if (x == INT_MIN) return 0; int r = 0, sign = x >= 0 ? 1 : -1, y = sign * x, p = 1; while (y) { y /= 10; if (y) p *= 10; } x = sign * x; while (x) { int d = x % 10; x /= 10; if ((INT_MAX - r) / p < d) return 0; r += p * d; p /= 10; } return sign * r; } };
-
class Solution: def reverse(self, x: int) -> int: y = int(str(abs(x))[::-1]) res = -y if x < 0 else y return 0 if res < -(2**31) or res > 2**31 - 1 else res ############ class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ sign = x < 0 and -1 or 1 x = abs(x) ans = 0 while x: ans = ans * 10 + x % 10 x /= 10 return sign * ans if ans <= 0x7fffffff else 0
-
func reverse(x int) int { ans, INT32_MAX, INT32_MIN := 0, math.MaxInt32, math.MinInt32 for ; x != 0; x /= 10 { if ans > INT32_MAX/10 || ans < INT32_MIN/10 { return 0 } ans = ans*10 + x%10 } return ans }
-
/** * @param {number} x * @return {number} */ var reverse = function (x) { let res = 0; while (x) { res = res * 10 + (x % 10); x = ~~(x / 10); } return res < Math.pow(-2, 31) || res > Math.pow(2, 31) - 1 ? 0 : res; };
-
# @param {Integer} x # @return {Integer} def reverse(x) neg = x < 0 x = x.abs s = '' x /= 10 while x > 0 && (x % 10).zero? while x > 0 s += (x % 10).to_s x /= 10 end s = neg ? '-' + s : s # have to explicitly constraint the int boundary as per the dummy test case res = s.to_i res <= 214_748_364_7 && res >= -214_748_364_8 ? res : 0 end
-
public class Solution { public int Reverse(int x) { var negative = x < 0; if (negative) x = -x; long result = 0; while (x > 0) { result = (result * 10) + x % 10; x /= 10; } if (negative) result = -result; if (result > int.MaxValue || result < int.MinValue) result = 0; return (int) result; } }
-
impl Solution { pub fn reverse(mut x: i32) -> i32 { let is_minus = x < 0; match x .abs() .to_string() .chars() .rev() .collect::<String>() .parse::<i32>() { Ok(x) => x * if is_minus { -1 } else { 1 }, Err(_) => 0, } } }