【Leetcode】Reverse Integer_整数反转_Easy2

本文思路参考:

作者:青猫123 
来源:CSDN 
原文:https://blog.csdn.net/superstar987/article/details/80426102 

整数反转题目:主要是要反转整数+判断溢出

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

 

这道题的要求是要反转整数,但是如果反转过后溢出的话,就要返回0;重点在于如何判断是否溢出。

 Answer:

class Solution
{
    public static int reverse(int num){
        {
            int length = 0;    //给出数的长度
            int rev = 0;
            if(num >= 0) length = (num+"").length();
            else length = (num+"").length();   //负数会占用一位符号位
            for(int i = 0; i < length; i++)      
            {
                int temp = num % 10;      //取最后一位数
                num = (num - temp) / 10;   //把最后一位抛掉以后得到的新的数
                rev += temp*Math.pow(10, length - i -1);    //反转数
            }
            
            if(rev > Math.pow(2, 32) - 1 || rev < (-1) * Math.pow(2, 31))  //判断溢出,简单暴力
                return 0;
            return rev;
        }
    }
}

 

 

public int reverse(int x) {
    long result = 0;
    while (x != 0) {
        result = result * 10 + x % 10;
        x /= 10;   //算法比上一种更加简单
    }
    if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)   //Integer.MAX_VALUE就是232
        result = 0;
    return (int)result;
}

 

 

 
posted @ 2018-11-26 19:10  白白要变成厉害的程序猿  阅读(134)  评论(0编辑  收藏  举报