【 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)
- Java long type error: error: integer number too large
- Develop a Boolean equation for overflow detection
- Java compareto() method
- Leetcode 832. Flip image
- Codeworks educational round 96 [reverse pair] E. string reverse
- [C + +] C + + overload operator = must be a nonstatic member function?
- Learn English together | three ways to realize digital factorial with JavaScript
- How to Use the Reverse() Function
- Java lossy conversion
- Reverse function: reverses container contents
- Creation and use of Oracle sequence
- The difference of four kinds of integer function (fix floor ceil round) in MATLAB
- Common errors and modification methods of findbug
- [Two Sigma OA] Longest Chain
- Python2 PicklingError: Can‘t pickle <type ‘instancemethod‘>: attribute lookup __builtin__.instanceme
- 43. Implementation of the shortest code of multiply strings | Java
- Differences between Java stack overflow ror and outofmemoryerror
- About java “Error: bad binary operator types”
- Matlab — looking for peak function