Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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 should 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 should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
解法一:把int数转为字符数组,使用进出栈进行逆序。
class Solution { public: int reverse(int x) { int neg = 1; if(x < 0) { neg = -1; x *= -1; } stack<char> stk; char temp[32]; sprintf(temp, "%d", x); string str; str = temp; for(string::size_type st = 0; st < str.length(); st ++) stk.push(str[st]); while(stk.size()>1 && stk.top() == ‘0‘) stk.pop(); string retstr; while(!stk.empty()) { retstr += stk.top(); stk.pop(); } return neg*atoi(retstr.c_str()); } };
解法二:将int数模10得到的每一位数字加入到返回值中,然后返回值乘10移位。
class Solution { public: int reverse(int x) { int neg = 1; if(x < 0) { x *= -1; neg = -1; } int ret = 0; while(x) { ret += x%10; x /= 10; ret *= 10; } return ret/10*neg; } };
【LeetCode】Reverse Integer (2 solutions)