Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

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?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

这道题很简单,题意就不说了,我的做法是把数字转化为字符串,然后反转字符串,Java中有StringBuilder,C++中有STL可以直接反转,假如超出范围,按照题意直接返回0即可。
代码如下:

import java.util.ArrayList;


public class Solution 
{
     public int reverse(int x) 
     {
         boolean isPos= x>=0? true :false;
         String res=new StringBuilder(Math.abs(x)+"").reverse().toString();      
         int fin=0;
         try {
             fin=isPos? Integer.parseInt(res.trim()) : -1*Integer.parseInt(res.trim());
        } catch (NumberFormatException e)
        {
            //字符串格式问题,超出Int的表示范围等等情况都按照0处理
            fin=0;
        }
         return fin;
     }

    public static void main(String[] args) 
    {
        Solution solution=new Solution();
        System.out.println(solution.reverse(1534236469));
    }
}

下面的是C++做法,就是使用long long 数据类型去处理溢出问题。

代码如下:

#include <iostream>
#include <limits>
#include <cmath>
using namespace std;


class Solution 
{
public:
    int reverse(int x) 
    {
        long long tmp = abs(x);
        long long res = 0;
        while (tmp > 0)
        {
            res = res * 10 + tmp % 10;
            if (res > numeric_limits<int>::max())
                return 0;
            tmp = tmp / 10;
        }
        return (x > 0)? (int)(res): (int)(-res);
    }
};