LeetCode——7. 整数反转

题目描述:

LeetCode——7. 整数反转

 

注:本分类博客中的所有代码可以直接拷贝到eclipise

代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/*  此方法也可以通过
  class Solution {  
	public int reverse(int x) {
		String str = String.valueOf(x);
		try {
			if (str.startsWith("-")) {
				String str1 = str.substring(1);
				StringBuilder res = new StringBuilder(str1).reverse();
				return Integer.parseInt("-" + res);
			} else {
				StringBuilder res = new StringBuilder(str).reverse();
				return Integer.parseInt("" + res);
			}
		} catch (NumberFormatException e) {
			return 0;
		}

	}
}*/
/**
 * 
 *
 * @版权 : Copyright (c) 2017-2018 *********公司技术开发部
 * @author: gaozhenchao
 * @E-mail: [email protected]
 * @版本: 1.0
 * @创建日期: 2019年1月23日 下午4:38:43
 * @ClassName Solution
 * @类描述-Description: 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
 * @修改记录:
 * @版本: 1.0
 */
class Solution {
	public int reverse(int x) {
		// 把整形转换成字符串
		String s = x + "";
		String t = "";
		// 把字符串转换成char数组
		char[] c = s.toCharArray();
		// 判断负号
		if (c[0] == '-') {
			// 单独处理负号
			t = "-";
			// 截取负号之后的值
			s = s.substring(1);
			// 重新给char数组赋值
			c = s.toCharArray();
		}

		// 新建一个数组,存储反转之后的数组
		char[] cc = new char[c.length];
		for (int i = 0; i < c.length; i++) {

			cc[i] = c[c.length - 1 - i];

		}
		// 字节数组转字符串
		s = t + String.valueOf(cc);
		// 用int转换会溢出 所以用long转换
		if (Long.parseLong(s) < Math.pow(-2, 31) || Long.parseLong(s) > Math.pow(2, 31) - 1) {
			return 0;
		}
		return Integer.parseInt(s);

	}
}

public class MainClass {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String line;
		while ((line = in.readLine()) != null) {
			int x = Integer.parseInt(line);

			int ret = new Solution().reverse(x);

			String out = String.valueOf(ret);

			System.out.print(out);
		}
	}
}