Leetcode(7)整数反转

package java_Leetcode;

import java.util.Scanner;

/**
 * 题目:给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
 * eg:123 -> 321
 *    -123 -> -321
 *    120  -> 21
 * @author hexiaoli
 * 思路:
 * 1)换成字符数组,然后根据中心进行反转,但这种情况没有考虑溢出。
 * 2)不断模10取最低位,在不断乘10,相加得到反转结果
 */
public class ReverseInteger {
	public static int reverseInteger1(int x) {
		char[] ch = Integer.toString(x).toCharArray();
		char temp =0;//临时变量
		//判断是正数还是负数
		if( x > 0 ) {
			//设置头尾指针
			int head =0;
			int tail = ch.length-1;
			//以ch.length/2为中心进行交换
			while(head < ch.length/2) {
				temp = ch[head];
				ch[head] = ch[tail];
				ch[tail] = temp;
				//头指针向前走,尾指针向后走
				head++;
				tail--;
			}
		}else if(x < 0 ){
			int head =1;//屏蔽负数符号影响
			int tail = ch.length-1;
			while(head < (ch.length-1)/2) {
				temp = ch[head];
				ch[head] = ch[tail];
				ch[tail] = temp;
				//头指针向前走,尾指针向后走
				head++;
				tail--;
			}	
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < ch.length; i++) {
			sb.append(ch[i]);
		}
		int res = 0;
		try {
			res = Integer.parseInt(sb.toString());
		} catch (Exception e) {
			throw new IllegalArgumentException("Overflow");
		}
		return res;
	}
	public static int reverseInteger2(int x) {
		int res = 0;
		while(x != 0) {
			int temp =x % 10;//取余
			x/=10;
			//java中int最大值为2^31-1=2147483647(nteger.MAX_VALUE)
			//最小值为-2^31+1=-2147483648(Integer.MIN_VALUE)
			//Integer.MAX_VALUE+1 = Integer.MIN_VALUE
			if(res > Integer.MAX_VALUE/10 || (res == Integer.MAX_VALUE / 10 && temp > 7))
				return 0;
            if (res < Integer.MIN_VALUE/10 || (res == Integer.MIN_VALUE / 10 && temp < -8))
            	return 0;			
			res = res*10+temp;
		}
		return res;
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int x = input.nextInt();
		System.out.println(reverseInteger1(x));
		System.out.println(reverseInteger2(x));
	}

}

猜你喜欢

转载自blog.csdn.net/hxl0925/article/details/89378247