LeetCode-Easy刷题(2) Reverse Integer

来源:互联网 发布:淘宝女鞋推荐 编辑:程序博客网 时间:2024/06/05 05:38

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

Example 1:

Input: 123Output:  321

Example 2:

Input: -123Output: -321

Example 3:

Input: 120Output: 21

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



给定一个32位的整数,一个整数的反数


  public int reverse(int x) {        if(x == Integer.MAX_VALUE){            return 0;        }        int num = Math.abs(x);        int rev = 0;        while(num!=0){            if(rev > (Integer.MAX_VALUE - num % 10)/10){                return 0;            }            rev  = rev*10 + num%10;            num = num/10;        }        return x>0? rev:-rev;    }


原创粉丝点击