LeetCode Reverse Integer, leetcodereverse
Reverse Integer Total Accepted: 61132 Total Submissions: 219035 My Submissions Question Solution
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x =-123, return-321
Click to show spoilers.
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.
Update (2014-11-10 ):
Test cases had been added to test the overflow behavior.
Exercise: reverse the number, but pay attention to the reverse order of 100 in case of overflow. In case of overflow, return the reverse order of 0,100 as 1 rather than 001.
First, the first solution is provided:
Since it is a reversal, the simplest thing is to regard the number as a string, and then perform a reverse order and a negative number for special processing. Then, use sscanf to convert the string into a number.
For overflow, assume that the input is x. If the backward direction overflows, the length of x is at least 10 characters. In addition, assume that the string after the backward direction is s1, the number after sscanf is y, so the string s2 corresponding to this y will be different from s1!
The Code is as follows:
Class Solution {public: int reverse (int x) {int result = 0; char s [12]; char r [12]; sprintf (s, "% d ", x); int I = 0; if (s [0] = '-') {r [0] = '-'; I ++ ;} r [strlen (s)] = '\ 0'; int j = strlen (s)-1; while (I <strlen (s )) {r [I] = s [j]; j --; I ++;} sscanf (r, "% d", & result); if (strlen (s)> = 10) // possible overflow {sprintf (s, "% d", result); if (strcmp (r, s) result = 0 ;} return result ;}};
1032/1032 test cases passed.
Status: Accepted
Runtime: 16 MS
Solution 2:
In fact, this is the simplest method. It is good to move the numbers in a single digit forward repeatedly. If overflow exists, 0 is returned directly!
Class Solution {public: int reverse (int x) {const int max = 0x7fffffff; // int maximum const int min = 0x80000000; // int minimum long sum = 0; while (x! = 0) {int temp = x % 10; sum = sum * 10 + temp; if (sum> max | sum <min) // return 0 for overflow processing; x = x/10;} return sum ;}};
1032/1032 test cases passed.
Status: Accepted
Runtime: 14 MS