【Coding!】Reverse Integer

原题:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

需求分析:

  1. 输入一个数,输出它的位数倒置数(123→321)
  2. 倒置溢出时,输出为0
  3. 负数倒置仍为负数

我的答案:

public class Solution {
    public int Reverse(int x) {
        Queue<int> queue=new Queue<int>();
        bool isNegative = checkNegative(ref x);
        int result=0;
        for(;;)
        {
            if(x==0)break;
            queue.Enqueue(pushIntger(ref x));
        }
        for(;;)
        {
            if(queue.Count()==0)break;
            if(!popIntger(ref result,queue.Dequeue())){
                result=0;
                break;
            }
        }
        return isNegative?-result:result;
    }

    public bool checkNegative(ref int num)
    {
        bool isNegative = false;
        if (num < 0)
        {
            isNegative = true;
            if (num == Int32.MinValue) num = 0;
            else num = Math.Abs(num);
        }

        return isNegative;
    }

    public int pushIntger(ref int num)
    {
        int temp=num%10;
        num/=10;
        return temp;
    }

    public bool popIntger(ref int num,int pop)
    {
        if(num>(Int32.MaxValue/10))return false;
        else if(num==(Int32.MaxValue/10)&&pop>7)return false;
        else {
            num=num*10+pop;
            return true;
        }
    }
}
//44ms,15M

原题答案:

class Solution {
    public int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据