LeetCode 007. Reverse Integer

30 篇文章 7 订阅
17 篇文章 2 订阅

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


这道题是要求进行数字翻转,一开始想到的是栈,代码略长,如下:

#define Maxnum 20

typedef struct 
{
    int data[Maxnum];
    int top;
}intstack;

void stackInit(intstack * sq)
{
    sq->top = -1;
}

bool stackEmpty(intstack * sq)
{
    if(sq->top == -1)
        return true;
    else 
        return false;
}

int push(intstack * sq, int a)
{
    if(sq->top == Maxnum-1)
    {
        return -1;
    }
    sq->top ++;
    sq->data[sq->top] = a;
    return 1;
}

int pop(intstack * sq, int &a)
{
    if(sq->top == -1)
        return -1;
    a = sq->data[sq->top];
    sq->top -- ;
    return 1;
}

class Solution 
{
public:
    int reverse(int x) 
    {
        intstack * sq = new intstack;
        stackInit(sq);
        //因为最小负数为-2147483648,最大正数为2147483647
        //因此x=0-x这种将负数转成正数的方法是不可取的!
        bool negative = false;
        if (x < 0)
            negative = true;
            
        int y = 0;
        //54321入栈,入栈顺序为1 -> 2 -> 3 -> 4 -> 5
        //-54321入栈,入栈顺序为-1 -> -2 -> -3 -> -4 -> -5
        while(x)
        {
            y = x%10;
            push(sq,y);   
            x = x/10;
        }
        x = 0;
        y = 0;
        int multi = 1;
        bool iszero = true;
        //将数据出栈
        while(!stackEmpty(sq))
        {
            pop(sq, y);

            if(!iszero || y)
            {
                x = x + y*multi;
                multi *= 10;
                iszero = false;
            }
        }

        return x;   
    }
};

后来在做palindrome Number时,又想到了另外一种方法:

class Solution 
{
public:
    int reverse(int x) 
    {
        int temp = x;
        int result = 0;
        while(temp)
        {
            result = result*10 + temp%10;
            temp /= 10;
        }
        return result;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值