Leetcode Note: Reverse Integer
I. Description
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x =-123, return-321
Ii. Question Analysis
Returns an integer. If it is a negative number, the negative number remains unchanged, and then the negative number is reversed. This question is simple, but it hides some traps, such as the overflow problem of the number after the reversal, and how to deal with it when the low position is 0 and the reverse is to the high position. The purpose of this question is not to examine an algorithm, but to check whether all kinds of boundary conditions are well considered. The code here is only Accept, which does not mean perfect.
Iii. Sample Code
Class Solution {public: int reverse (int x) {long result = 0; const int max = 0x7fffffff; // int maximum value const int min = 0x80000000; // int minimum value for (; x! = 0; x/= 10) {result = result * 10 + x % 10; if (result> max | result <min) result = 0; // beyond the 32-bit int range, set 0} return result ;}};
Iv. Summary
For some seemingly simple questions, the more you need to consider some boundary conditions, and these can also bring you extra points during the written examination or interview.