当前位置 : 主页 > 编程语言 > c++ >

【Leetcode】Reverse Integer

来源:互联网 收集:自由互联 发布时间:2021-06-30
ReverseInteger.java /** * 7. Reverse Integer * Reverse digits of an integer. * Example1: x = 123, return 321 * Example2: x = -123, return -321 * The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reve
ReverseInteger.java
/**
	 * 7. Reverse Integer
	 * Reverse digits of an integer.
	 * Example1: x = 123, return 321
	 * Example2: x = -123, return -321
	 * The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
	 * @param x
	 * @return
	 */
	public static int reverseInteger(int x) {
		int devF = 1;
		int devR = 1;
		int base = 1;
		if (x < 0) {
			x = 0 - x;
			base = -1;
		}		
		int tmp = x;
		while (tmp > 10) {
			tmp = tmp / 10;
			devF *= 10;
		}		
		int result = 0;
		while (devF > 10) {			
			int first = x / devF;
			int last = x % 10;			
			result += (base*(last*devF+first*devR));			
			x = x- devF*first - devR*last;			
			devF /=10;
			devR *=10;			
			if(devF==10){
				result += base*(x/devF)*devR;
				break;
			}		
		}
		return result;
	}
网友评论