【Leetcode】Reverse Integer_整数反转_Easy2

本文思路参考:git

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

算法

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

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

Example 1:.net

Input: 123
Output: 321

Example 2:code

Input: -123
Output: -321

Example 3:blog

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.it

 

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

 Answer:function

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;
}
相关文章
相关标签/搜索