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

    class Solution {
    public:
        int reverse(int x) {
            unsigned long long result=0;
            if (INT_MIN == x||0==x)return 0;
            bool plus_or_minus_tag = true;
            if (x < 0)
            {
                x = -x;
                plus_or_minus_tag = false;
            }
            while (x)
            {
                result = result * 10 + x % 10;
                x /= 10;
            }
            if (plus_or_minus_tag)
            {
                if (result > 2147483647)
                    return 0;
                else return int(result);
            }
            else
            {
                if (result > 2147483647)
                    return 0;
                else return 0 - int(result);
            }
        }
    };
  • 相关阅读:
    hdu 1312 ( Red and Black )
    hdu 1429 ( 胜利大逃亡(续) )
    zjut 小X的苹果
    hdu 1253 ( 胜利大逃亡 )
    许多事
    1198 ( Farm Irrigation )
    hdu 1241 Oil Deposits
    hdu 1242 ( Rescue )
    hdu 1240 ( Asteroids! )
    zoj2966 build the electric system
  • 原文地址:https://www.cnblogs.com/csudanli/p/5890164.html
Copyright © 2011-2022 走看看