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

    链接:https://leetcode.com/problems/reverse-integer/

    一刷

    Python

    Python里int可以自动向上转换成long,long是保留精度的数据类型,无范围限制。int的上限为sys.maxint(Python2)和sys.maxsize(Python3),下限对应。

    class Solution(object):
        def reverse(self, x):
            """
            :type x: int
            :rtype: int
            """
            if x == 0:
                return x
            negative = bool(x < 0)
            process_num = -x if negative else x
            revert_num = 0
            min_int = -2147483648
            max_int = 2147483647
            try:
                while process_num:
                    mod = process_num % 10
                    if -revert_num < min_int / 10 or revert_num > max_int / 10:
                        return 0
                    revert_num = revert_num * 10 + mod
                    process_num = process_num / 10
                return -revert_num if negative else revert_num
            except ValueError as error:
                print error.message
            except Exception as error:
                raise error

    2/6/2017, Java刷题

    用新的语言每道题都很困难,有些是算法,有些是因为语言。

     1 public class Solution {
     2     public int reverse(int x) {
     3         if (x < 10 && x > -10) return x;
     4 
     5         int temp = 0;
     6         int digit = 0;
     7         
     8         while ( x != 0 ) {
     9             digit = x % 10;
    10             x = x / 10;
    11             if (Integer.MAX_VALUE / 10 < temp) return 0;
    12             if (Integer.MIN_VALUE / 10 > temp) return 0;
    13             temp = 10 * temp + digit;
    14         }
    15         return temp;
    16     }
    17 }

    出现的错误:

    1. Integer.MAX_VALUE, NOT Integer.MAX_INT

    2. temp初始值不是0,是1,导致所有答案前面多了一位1

    3. 只有个位数的输入不应该经过算法,应该直接返回

    4. 第3行返回不是x而是0

    5. Math.abs(-2147483648)会溢出

    6. sign其实是不需要的,%, /都会保留符号

  • 相关阅读:
    PHP 使用 GET 传递数组变量
    Java实现 蓝桥杯 算法训练 数据交换
    Java实现 蓝桥杯 算法训练 数据交换
    Java实现 蓝桥杯 算法训练 数据交换
    Java实现 蓝桥杯 算法训练 景点游览
    Java实现 蓝桥杯 算法训练 景点游览
    Java实现 蓝桥杯 算法训练 景点游览
    Java实现 蓝桥杯 算法训练 二进制数数
    Java实现 蓝桥杯 算法训练 二进制数数
    Java实现 蓝桥杯 算法训练 二进制数数
  • 原文地址:https://www.cnblogs.com/panini/p/5545148.html
Copyright © 2011-2022 走看看