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

    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.

    提示:

    此题的关键是要解决溢出这一特殊情况,有两种解决方法:

    1. 声明一个long long型变量,返回之前检查其大小是否溢出;
    2. 在每一次循环过程中对数值检测。

    代码:

    方法1:

    class Solution {
    public:
        int reverse(int x) {
            long long int result = 0;
            while (x) {
                result = 10 * result + x % 10;
                x = x / 10;
            }
            return result > std::numeric_limits<int>::max() || result < std::numeric_limits<int>::min() ? 0 : result;
        }
    };

    方法2:

    class Solution {
    public:
        int reverse(int x) {
            if (x == INT_MIN)
                return 0;
            if (x < 0)
                return -reverse(-x);
    
            int rx = 0; // store reversed integer
            while (x != 0) {
                // check overflow
                if (rx > INT_MAX / 10 || 10 * rx > INT_MAX - x % 10) return 0;
                rx = rx * 10 + x % 10;
                x = x / 10;
            }
            return rx;
        }
    };
  • 相关阅读:
    Ubuntu 18.04.2 LTS美化方案
    Ubuntu 16.04升级18.04
    Spark性能优化指南——高级篇
    Spark性能优化指南——基础篇
    遗传算法(Genetic Algorithm)——基于Java实现
    Linux sar命令参数详解
    Gdb调试多进程程序
    P8.打印整数
    Algorithm Book Index
    Debugging with GDB (8) 4.10 Debugging Programs with Multiple Threads
  • 原文地址:https://www.cnblogs.com/jdneo/p/4754026.html
Copyright © 2011-2022 走看看