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.

    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;
        }
    }
  • 相关阅读:
    遍历数组的常用方法
    ios 提审被拒4.3,更换账号提审处理
    js 判断手机有没有网络
    js网页拉起支付宝支付
    uni-app常用 HTML5+APP 设置
    uni-app 无痛刷新 token 方法
    uni-app通过判断接口403跳转登录页面的问题
    APICloud项目纪要
    Vue递归组件实现层层嵌套显示数据
    Git恢复删除的分支
  • 原文地址:https://www.cnblogs.com/strugglion/p/6391442.html
Copyright © 2011-2022 走看看