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其实是不需要的,%, /都会保留符号

  • 相关阅读:
    转载 从最简单的vector中sort用法到自定义比较函数comp后对结构体排序的sort算法
    TYVJ P1081 最近距离 Label:这不是分治!!!
    TYVJ P1086 Elevator Label:dp
    数字图像处理的三个层次
    栅格化是什么意思?
    图像基本知识
    修改了天空盒子但是点play还是没变原因
    地形编辑
    Bmp8位图像亮度如何调整?
    bmp图像作业笔记
  • 原文地址:https://www.cnblogs.com/panini/p/5545148.html
Copyright © 2011-2022 走看看