7. Reverse Integer

题目:翻转整数

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,result = result * 10 + x % 10;假如x / 10 != 0,则继续将余数按照前面的方式添加到result中

注意:整数最大取值为:2147483647,最小的取值为:-2147483648,处理result时候,需要注意先将result与最大整数,最小整数求余的值进行比较。

java代码:

public class ReverseInteger {
    public static int reverse(int x) {
        int result = 0;
        do{
            if(result > Integer.MAX_VALUE / 10 || (result == Integer.MAX_VALUE / 10 && x % 10 > 7)) return 0;
            if(result < Integer.MIN_VALUE / 10 || (result == Integer.MIN_VALUE / 10 && x % 10 < -8)) return 0;
            result = result * 10 + x % 10;
        }while((x = x / 10) != 0);
        return result;
    }

    public static void main(String[] args){
        int result = reverse(1534236469);
        System.out.println(result);
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MIN_VALUE);
        System.out.println(-14 / 10);
        System.out.println(-14 % 10);
    }
}

result:

0
2147483647
-2147483648
-1
-4

posted @ 2019-03-10 12:15  风影旋新月  阅读(272)  评论(0编辑  收藏  举报