LeetCode 007. Reverse Integer

来源:互联网 发布:先锋乒羽淘宝商城微店 编辑:程序博客网 时间:2024/06/14 05:23

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 20typedef 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;    }};




0 0
原创粉丝点击