首页 > 代码库 > Reverse Integer

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).

 1 class Solution { 2 public: 3     int reverse(int x) { 4          5         int flag = 0; 6         if(x < 0) 7         { 8             flag = -1; 9             x = -x;10         }11         12         int result = 0;13         int k = 1;14         vector<int> figure;15         16         while(x / 10 != 0)17         {18             figure.push_back(x % 10);19             x /= 10;20         }21         figure.push_back(x);22         23         for(int i = figure.size()-1; i >= 0; i--, k *= 10)24         {25             result += figure[i] * k;26         }27         28         if(flag == -1)29             result = -result;30             31         return result;32     }33 34 };

 

Reverse Integer