Leetcode -- 7 Reverse Integer (with the implementation of overflow Integer flip), leetcodereverse
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x =-123, return-321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what shoshould the output be? Ie, cases such as 10,100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How can you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Hide Tags: Math
Solution:
(1) separate from the low position of the given number n: int s = n % 10;
(2) perform the equivalent flip operation on the number of splits: sum = sum * 10 + s. To prevent overflow, define the sum type as long.
(3) n/= 10; continue the loop operation
(4) Check for overflow: If sum> Integer. MAX_VALUE | sum <Integer. MIN_VALUE, overflow exists and 0 is returned. If no overflow exists, convert the sum type to int.
The Code is as follows:
Public static int reverse (int n) {// The output result is defined as longlong sum = 0; while (n! = 0) {int s = n % 10; sum = sum * 10 + s; n = n/10;} // prevent overflow operation if (sum> Integer. MAX_VALUE | sum <Integer. MIN_VALUE) {return 0;} return (int) sum ;}