Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Naive Solution
Naive solution with C++ is using mod operator to get the right-most bit of number, accumulate to a result.
Note 1: If input is 0, return 0 as result directly.
Note 2: Remember to test valid integer range in the loop, using long long for simple logic.
#define LL long long classSolution { public: intreverse(int x){ if(x == 0) return0; LL res = 0; LL val = (LL)x; while(val) { res = res * 10 + (val % 10); if(res > (LL)INT_MAX || res < (LL)INT_MIN) return0; val /= 10; } return res; } };
If we don’t use long long type, it will be more complicated to number range validation.
classSolution { public: intreverse(int x){ if(x == 0) return0; int res = 0; while(x) { if((x>0 && res <= INT_MAX/10 && res*10 <= INT_MAX - x%10) || (x<0 && res >= INT_MIN/10 && res*10 >= INT_MIN - x%10)) res = res * 10 + (x % 10); else return0; x /= 10; } return res; } };
Approach with string
If you don’t want the numeric operations, another approach is convert the integer into string. In this way we don’t need to care the number range issue, but need to take care the negative corner cases.