Problem:
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?
Throw an exception? Good, but what if throwing an exception is not an option? You wowould then have to re-design the function (ie, add an extra parameter ).
Analysis:
A simple analysis is relatively simple to reverse an integer. The Code is as follows:
public class Solution { public int reverse(int x) { int result = 0; while(x != 0){ result = result*10+x%10; x = x/10; } return result; }}
The above code changes the number to 10100 after it is reversed like 101, which is acceptable, but the overflow problem is not considered.
Considering overflow,
First, we can record the original number of signs X. in Java, the sign bit of X can be obtained as int Sign = x> 31. If sign is-1, it indicates a negative number. Otherwise, it is positive.
Then, calculate the inverse number result according to the above method, and then judge whether the signed bit of the result is the same as the original number X. If the result is the same, no overflow exists; otherwise, the result overflows.
The implementation code is as follows:
public int reverse2(int x) { int result = 0; int sign = x>>31; while (x != 0) { result = result * 10 + x % 10; x = x / 10; }// System.out.println(sign+", "+(result>>31)); if(sign!=(result>>31)){ System.out.println("overflow.."); System.exit(1); } return result; }
The complete code for testing is as follows:
public class ReverseInt { public static void main(String[] args) { ReverseInt r = new ReverseInt(); System.out.println(r.reverse2(123)); System.out.println(r.reverse2(1230)); System.out.println(r.reverse2(-123)); System.out.println(r.reverse2(1000000003)); } public int reverse(int x) { int result = 0; while (x != 0) { result = result * 10 + x % 10; x = x / 10; } return result; } public int reverse2(int x) { int result = 0; int sign = x>>31; while (x != 0) { result = result * 10 + x % 10; x = x / 10; }// System.out.println(sign+", "+(result>>31)); if(sign!=(result>>31)){ System.out.println("overflow.."); System.exit(1); } return result; }}
Leetcode -- reverse INTEGER (returns an integer)