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.

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

    注意:OJ更新了溢出测试,所以还是要考虑溢出。

    Java:

    public class Solution {
        public int reverse(int x) {
            long result = 0;
            int tmp = Math.abs(x);
            while(tmp>0){
                result *= 10;
                result = result * 10 + tmp % 10;
                if(result > Integer.MAX_VALUE){
                    return 0;
                }
                tmp /= 10;
            }
            return (int)(x>=0?result:-result);
        }
    }

    Python:

    class Solution(object):
        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            if x < 0:
                return -self.reverse(-x)
    
            result = 0
            while x:
                result = result * 10 + x % 10
                x //= 10
            return result if result <= 0x7fffffff else 0  # Handle overflow.
    

    C++:

    class Solution {
    public:
        int reverse(int x) {
            int res = 0;
            while (x != 0) {
                if (abs(res) > INT_MAX / 10) return 0;
                res = res * 10 + x % 10;
                x /= 10;
            }
            return res;
        }
    };
    

    C++:

    class Solution {
    public:
        int reverse(int x) {
            int result = 0;
            while (x) {
                auto prev = result;
                result *= 10;
                result += x % 10;
                if (result / 10 != prev) {
                    result = 0;
                    break;
                }
                x /= 10;
            }
            return result;
        }
    };
    

     

    类似题目:

    [LeetCode] 190. Reverse Bits 翻转二进制位

     

    All LeetCode Questions List 题目汇总

      

  • 相关阅读:
    Hive-1.2.1_05_案例操作
    Hive-1.2.1_04_DML操作
    Hive-1.2.1_03_DDL操作
    Hive-1.2.1_02_简单操作与访问方式
    Hive-1.2.1_01_安装部署
    Hadoop2.7.6_08_Federation联邦机制
    Hadoop2.7.6_07_HA高可用
    NFS服务搭建与配置
    Hadoop2.7.6_06_mapreduce参数优化
    Hadoop2.7.6_05_mapreduce-Yarn
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8488923.html
Copyright © 2011-2022 走看看