码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Reverse Integer (2 solutions)

时间:2014-08-21 19:07:04      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   使用   io   strong   

Reverse Integer

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?

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());
    }
};

bubuko.com,布布扣

 

解法二:将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;
    }
};

bubuko.com,布布扣

【LeetCode】Reverse Integer (2 solutions),布布扣,bubuko.com

【LeetCode】Reverse Integer (2 solutions)

标签:des   style   blog   http   color   使用   io   strong   

原文地址:http://www.cnblogs.com/ganganloveu/p/3927722.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!