【 Problem Description 】
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
[thinking]
This problem seems simple, but there are more pits.
Integer inversion is a simple problem, but overflow needs to be dealt with.
Save the result as a long, returning 0 if it is greater than the integer maximum or less than the negative minimum
[code]
public class Solution {
public int reverse(int x) {
if (x == 0) {
return 0;
}
int sign = 1;
if (x < 0) {
sign = -1;
}
long result = 0;
long t = Math.abs((long) x);
while (t != 0) {
result = result * 10 + t % 10;
;
t /= 10;
}
if ((sign == 1 && result > Integer.MAX_VALUE)
|| (sign == -1 && sign * result < Integer.MIN_VALUE)) {
return 0;
}
return sign * (int) result;
}
}
Read More:
- 7. Reverse Integer [easy] (Python)
- LeetCode 23. Merge k Sorted Lists(java)
- Leetcode solution 189 Rotate Array Java version
- Java long type error: error: integer number too large
- There is no getter for property named ‘id‘ in ‘class java.lang.Integer‘
- Reverse function: reverses container contents
- How to Use the Reverse() Function
- Codeworks educational round 96 [reverse pair] E. string reverse
- Leetcode 832. Flip image
- 206. Reverse Linked List [easy] (Python)
- Nginx reverse proxy MySQL
- 【Hackerrank】Reverse a doubly linked list
- The sum of the two numbers of leetcode
- LeetCode 332. Reconstruct Itinerary
- IOS reverse error: use of undeclared identifier ‘mshookivar’
- Leetcode-234: palindrome linked list
- Common causes of Leetcode Runtime Error
- Mybatis reverse problem failed to load ApplicationContext
- Nginx reverse proxy report 400 error solution!
- [Err] ERROR: invalid input syntax for integer: “1.0”