Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

题目解析:翻转数字,本题看似简单其实暗藏杀机,主要还是边界问题,输入大数翻转后不溢出


解法一(RunTime Error):数字转字符处理然后再回归数字,利用java自身API从后往前append到新串,但是没有通过大数边界

/*public int reverse(int x) {
		// 数字转字符处理
		long result = 0;
		int flag = 1;// x正负判断
		StringBuilder sb = new StringBuilder();
		String temp = String.valueOf(Math.abs(x));
		if (x < 0)
			flag = -1;

		for (int i = temp.length() - 1; i >= 0; i--) {
			sb.append(temp.charAt(i));
		}
		result = Long.valueOf(sb.toString());
		if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)
			return 0;
		
		return (int) (result * flag);
	}*/

解法二(AC):从问题本质入手,将余数扩大10倍然后累加和,不通过字符串和数字互转,最后判断一下是否存在大数溢出即可

public int reverse(int x) {
    	long reverse = 0;
        //余数按照10倍扩大累加
        while(x != 0){
        	reverse = reverse * 10 + x % 10;
        	if(reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE)
        		return 0;
        	x = x / 10;
        }
        return (int)reverse;
    }


你可能感兴趣的:(LeetCode)