[Algorithm] 10. Reverse Integer
Description
Given a 32-bit signed integer, reverse digits of an integer.
Example
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
Note
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution
int reverse(int x) { bool minus_flag = false; bool zeroIgnore = true; int result=0; stack<char> numPool; if( x < 0 ){ x = -x; minus_flag = true; } if( x/10 == 0 ){ return minus_flag ? -x : x; } // Put each number into Stack container. while(x){ if ( x % 10 ) { numPool.push(x % 10); zeroIgnore = false; }else{ if ( !zeroIgnore ) numPool.push(0); } x = x/10; } // Calculate total sum. int cnt=numPool.size(); for(int i=0; i<cnt; i++) { result+=numPool.top() * pow(10, i); // Judge if the result overflows. if (result < numPool.top() * pow(10, i) ) { return 0; } numPool.pop(); } return minus_flag ? -result : result; }