zoukankan      html  css  js  c++  java
  • 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?

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

    最近做的几题好像都是考数学相关的,所以界限以及判断很重要。
     
    如果为最小的负数,应该直接返回0,而不能将其转换为正数之后再转换为负数。
     
    C++代码如下:
    #include<iostream>
    #include<climits>
    using namespace std;
    
    class Solution
    {
    public:
        int reverse(int x)
        {
            //如果x刚好等于INT_MIN,那么不能先将x转换为正数然后转换为负数
            if(x==0||x==INT_MIN)
                return 0;
            int flag=1;
            if(x<0)
            {
                x=-x;
                flag=-1;
            }
            long long i=1;
            long long j=10;
            while(i<=x)
            {
                i*=10;
            }
            i=i/10;
            long long sum=0;
            while(j<=i)
            {
                sum+=(x/i)*(j/10)+(x%j)/(j/10)*i;
    
                if(flag==1&&sum>INT_MAX)
                    return 0;
                else if(flag==-1&&-sum<INT_MIN)
                    return 0;
                x=x%i;
                i/=10;
                j*=10;
            }
            //如果是奇数位,中间的数没有加上去,如果位数为奇数位,那么最后i与j相差10倍,否则i与j相差100倍
            if(j==i*10)
                sum+=(x/i)*(j/10);
            if(flag==1&&sum>INT_MAX)
                return 0;
            else if(flag==-1&&-sum<INT_MIN)
                return 0;
            return flag*sum;
        }
    };
    int main()
    {
        Solution s;
        cout<<s.reverse(-2147483648)<<endl;
    }

    方法二:

        int reverse(int x) {
            if(x==0||x==INT_MIN)
                return 0;
            int flag=1;
            if(x<0)
            {
                x=-x;
                flag=-1;
            }
            long long res=0;
            while(x)
            {
                res=res*10+x%10;
                x/=10;
            }
            if((flag==1&&res>INT_MAX)||-res<INT_MIN)
                return 0;
            return flag*res;
        }
  • 相关阅读:
    QTP 11.05下载并完成+皴
    ZOJ Monthly, June 2014 月赛BCDEFGH题题解
    Linux makefile 教程 很具体,且易懂
    oracle中imp命令具体解释
    html5实现摇一摇
    AfxMessageBox和MessageBox差别
    Android传感器概述(六)
    线性代数之矩阵与坐标系的转换
    測试新浪微博@小冰 为代码机器人的一些方法
    破解中国电信华为无线猫路由(HG522-C)自己主动拨号+不限电脑数+iTV
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4099138.html
Copyright © 2011-2022 走看看