LintCode 413. 反转整数

Posted 走在修行的大街上

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LintCode 413. 反转整数相关的知识,希望对你有一定的参考价值。

题目:

  • LintCode 413. Reverse Integer
  • 将一个整数中的数字进行颠倒,当颠倒后的整数溢出时,返回 0 (标记为 32 位整数)。

样例:

  • 给定 x = 123,返回 321
  • 给定 x = -123 ,返回 -321

实现:

  • Java实现代码

    public class Solution {
    /**
     * @param n: the integer to be reversed
     * @return: the reversed integer
     */
    public int reverseInteger(int n) {
            // write your code here
            boolean negative = n < 0;
            if(negative) n = -n;
            long r = 0;
            while(n>0){
                r = r*10 + n%10;
                n=n/10;
            }
            if(negative) r = -r;
            if(r>Integer.MAX_VALUE||r<Integer.MIN_VALUE) return 0;
            return (int)r;
        }
    }

以上是关于LintCode 413. 反转整数的主要内容,如果未能解决你的问题,请参考以下文章