Reverse Integer leetcode
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.
The question indicates that an integer needs to be reversed. When the reversed number overflows, 0 is returned.
Note the following:
When the input is INT_MIN, it is indicated by the computer completion code. If the input is on a 32-bit machine
The INT_MIN binary code is 10000000 00000000 00000000 00000000
Many people must have ignored a detail. When INT_MIN's inverse number is used, it cannot be 2147483648 (Power 32 of 2)
Because the computer performs the x =-x operation, the multiplication operation-1 of the complement code in the computer is the complement code of the original code, except the symbol bit, which is reversed by 1.
-The Source Code of 1 is 10000000 00000000 00000000 00000001, and the code is reversed to 11111111 11111111 11111111 11111111.
Therefore, when the complement multiplication method is 10000000 00000000 00000000 00000000*11111111 11111111 11111111, the overflow part is obviously discarded.
10000000 00000000 00000000 00000000, that is, INT_MIN? x =-x. Not only 0 is set up, but INT_MIN is set up on a limited machine.
The Code is as follows:
Class Solution {public: int reverse (int x) {bool negative_flag = false; // if (x = INT_MIN) // It must be determined that it should be INT_MIN. In order to make it easy to perform the x =-x operation with an eight-bit binary value of 1000 0000, the computer will multiply it by a complement code, -The complement Code of 1 is the original code. In addition to the symbol bit, it is reversed by adding 1, that is, 1000, 0001, and 1111. The complement code is changed to 1111, therefore, x =-x becomes the complement code multiplication 1000 0000*1111 1111 1000 = 0000, and x is equal to INT_MIN. Therefore, when x in the while LOOP does not have a positive number. Return 0; if (x <0) {x =-x; negative_flag = true;} long result = 0; while (x! = 0) {result = result * 10 + x % 10; x = x/10;} if (result> INT_MAX) return 0; if (negative_flag) return-result; else return result ;}};