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

    Update (2014-11-10):
    Test cases had been added to test the overflow behavior.

    Subscribe to see which companies asked this question

     
    解法1:使用to_string、std::reverse、stoll库函数。注意到旋转后可能溢出,因此设置临时变量时应该为long long,然后判断并处理。
    class Solution {
    public:
        int reverse(int x) {
            string s = to_string(x);
            if (s[0] == '-')
                std::reverse(s.begin() + 1, s.end());
            else
                std::reverse(s.begin(), s.end());
            long long n = stoll(s);
            if (n > INT_MAX || n < INT_MIN) return 0;
            return n;
        }
    };

    解法2:先判断输入的正负,然后对绝对值处理,每次取末位相加,最后判断是否溢出。

    class Solution {
    public:
        int reverse(int x) {
            long long res = 0;
            bool isNegative = false;
            if (x < 0) {
                x = -x;
                isNegative = true;
            }
            while (x > 0) {
                res *= 10;
                res += x % 10;
                x /= 10;
            }
            if (res > INT_MAX) return 0;
            return isNegative ? -res : res;
        }
    };

    实际上不需要事先判断输入的正负,因为在取余的时候会自动包含进去,此时while循环的结束条件是x!=0。

    class Solution {
    public:
        int reverse(int x) {
            long long res = 0;
            while (x != 0) {
                res *= 10;
                res += x % 10;
                x /= 10;
            }
            if (res > INT_MAX || res < INT_MIN) return 0;
            return res;
        }
    };
  • 相关阅读:
    C指针
    redis五种基本数据类型
    mongoDB MapReduce
    JSON传参
    mongodb查询实练
    逻辑数据结构和存储数据结构
    线性表的顺序存储和链式存储
    数据结构和算法关系
    UIActivityIndicatorView使用
    Swift中格式化日期
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4949933.html
Copyright © 2011-2022 走看看