LeetCode之7. Reverse Integer

7. Reverse Integer

Easy

17852534FavoriteShare

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.

       我自己的代码,不能ac
 

class Solution {
    
    public  int reverse(int x) {
		
		if(x > Integer.MAX_VALUE || x < Integer.MIN_VALUE){
			return 0;
		}
		
		boolean flag = false;
		if(x < 0){
			flag = true;
			x = -x;
		}
		
		StringBuilder sb = new StringBuilder();
		while(x != 0){
			int temp = x % 10;
			x = x / 10;
			if(temp != 0){
				sb.append(temp);
			}
		}
		String str = sb.toString();
		int result = Integer.valueOf(str);  // LeetCode上这句,编译不通过
		
		return flag ? -result : result;
	}
}

 别人的代码,可以AC

class Solution {
    
    public int reverse(int x) {

        if(x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) return 0;

        // 注意,这里换成了long类型,不能继续使用int类型,否则数颠倒后,可能会溢出
        long result = 0;
        int tmp_x = Math.abs(x);

        while(tmp_x != 0){
            result = (result * 10) + tmp_x % 10;
            tmp_x /= 10;
        }

        // 这一步不能少
        // 一个数正向不溢出时,颠倒后可能变成溢出的;
        if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) return 0;

        return (int)(x < 0 ? -result : result);
    }
}

猜你喜欢

转载自blog.csdn.net/iNiBuBian/article/details/85171550