• [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.

    Note:
    The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

    解法: 

      翻转数字问题需要注意的就是溢出问题,为什么会存在溢出问题呢,我们知道int型的数值范围是 -2147483648~2147483647, 那么如果我们要翻转 1000000009 这个在范围内的数得到 9000000001,而翻转后的数就超过了范围。

      因此,可以采用double类型存储翻转后的数,再与 Integer.MAX_VALUE 和 Integer.MIN_VALUE 比较,判断是否溢出。

      此处并不需要在意正负数的情况,对结果没有影响,因为:12 % 10 = 2;  -12 % 10 = -2

    public class Solution {
        public int reverse(int x) {
            double res = 0;
            while (x != 0) {
                res = res * 10 + x % 10;
                x /= 10;
            }
            if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE)
                return 0;
            else
                return (int)res;
        }
    }
  • 相关阅读:
    搞IT的不如去养鸡养猪了
    matlabemacs运行matlab程序出错.不能调用matlab命令行模式
    微软利用全球天文望远镜数据建立宇宙地图
    程序人生2005年(30)
    IT领袖峰会精彩观点:4G时代不存在信令问题
    初识MySql数据库
    Android屏幕尺寸适配注意事项
    Java多线程详解(一)
    ios键盘高度
    ASP.NET MVC——Action的执行
  • 原文地址:https://www.cnblogs.com/strugglion/p/6391442.html
Copyright © 2020-2023  润新知