资讯专栏INFORMATION COLUMN

[LintCode] Reverse Integer

The question / 270人阅读

摘要:这道题有一些细节需要留意。新数会不会溢出符号位如何处理用惯用的做法,除以取余,得到最低位,放进。每次循环乘以累加当前最低位,同时除以不断减小。要点在于考虑乘累加运算的情况,用分支语句判断发生溢出的条件。最后的结果要加上之前排除的符号位。

Problem

Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).

Example

Given x = 123, return 321

Given x = -123, return -321

Note

这道题有一些细节需要留意。新数res会不会溢出?符号位如何处理?
用惯用的做法,n除以10取余,得到最低位cur,放进res。每次循环res乘以10累加当前最低位cur,同时n除以10不断减小。
要点在于考虑res乘10累加运算的情况,用分支语句判断发生溢出的条件。不能直接写if (res * 10 + cur > Integer.MAX_VALUE),因为res * 10就有可能会溢出了;而要用(Integer.MAX_VALUE - cur) / 10,因为只有减法和除法,结果不可能溢出。
最后的结果要加上之前排除的符号位。

Solution
public class Solution {
    public int reverseInteger(int n) {
        boolean isNeg = n < 0;
        n = isNeg ? -n : n;
        int res = 0;
        while (n != 0) {
            int cur = n % 10;
            if (res >= (Integer.MAX_VALUE - cur) / 10) return 0;
            res = res * 10 + cur;
            n /= 10;
        }
        return isNeg ? -res : res;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65555.html

相关文章

  • [LintCode] Evaluate Reverse Polish Notation

    摘要:中的运算符,运算之后要出来,继续遍历数组。是放入新的数字,用转换为均可。 Problem Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another ...

    luckyyulin 评论0 收藏0
  • LintCode】Expression Expand 非递归stack完成DFS(String)

    摘要:直接的方法不可取因为是每一层。层直接从取出实际上是将这个后应该得到。这个时候考虑逆向,建立一个,将出来的东西再一个顺序,逆逆得顺是一个很好用的操作符,判断一个对象是否是一个类的实例。坑小心一点这种情况啊代码 这道题真是超级棒的stack DFS样板题啊,在这里给自己写个小小的总结 思路:想到stack并不难,这种嵌套式一般是DFS的思想,先走到最里面最小的那个括号,然后逐渐回到上一层→...

    livem 评论0 收藏0
  • 表达式类算法题小结

    摘要:将表达式转换为逆波兰式,然后求值转换中缀表达式为逆波兰式鲁棒性检测,表达式中没有操作数计算逆波兰式值参考 表达式类算法题小结 [TOC] 声明 文章均为本人技术笔记,转载请注明出处:[1] https://segmentfault.com/u/yzwall[2] blog.csdn.net/j_dark/ 表达式分类 根据运算符与相关操作操作数的位置不同,将表达式分为前缀,中缀和后缀表...

    Heier 评论0 收藏0
  • [LeetCode/LintCode] Top K Frequent Words

    LeetCode version Problem Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, t...

    0x584a 评论0 收藏0
  • [LintCode] Reverse Pairs

    摘要:暴力解法就是时灵时不灵,两次一次。希望看到的大神能够分享优质的解法谢谢大家 Problem For an array A, if i < j, and A[i] > A[j], called (A[i], A[j]) is a reverse pair.return total of reverse pairs in A. Example Given A = [2, 4, 1, 3, ...

    tigerZH 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<