首页 > 代码库 > leetcode - Reverse Integer
leetcode - Reverse Integer
题目:Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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).
1 #include <string> 2 #include <iostream> 3 4 using namespace std; 5 6 class Solution 7 { 8 public: 9 int reverse(int x)10 {11 char x_chars[64];12 int x_value =http://www.mamicode.com/ abs(x);13 14 if (x < 0)15 {16 sprintf(x_chars, "%d-", x_value);17 }18 else19 {20 sprintf(x_chars, "%d", x_value);21 }22 string x_string(x_chars);23 string x_reverse(x_string.rbegin(), x_string.rend());24 25 return atoi(x_reverse.c_str());26 }27 };28 29 int main()30 {31 Solution s;32 int test = s.reverse(-123490);33 34 cout << test << endl;35 36 system("pause");37 38 return 0;39 }
上网看了几篇文章,都是通过除以10和模10的方法来取得尾数,有一遍文章有对溢出问题的思考,链接:http://blog.csdn.net/littlestream9527/article/details/17059939