整数反转
整数反转:
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
leetcode官方解答:
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}
我的解答:
import java.util.*;
//先将输入的整数转化成字符串
//然后转换为字符型数组
//再倒置略去高位上的0
//产生倒置后的字符串,再将字符串转换成整型对象,最后将整形对象变为整数输出。
//注意:字符串转换成整型对象时可能溢出
public class reverse {
public int reverse(int x) {
if(x == 0) return 0;
String str1 = "" + x;
String str2 = reverseCharArray(str1);
try {
Integer integer=Integer.valueOf(str2);
int num = integer.intValue();
return num;
}catch(Exception e) {
return 0;
}
}
public static String reverseCharArray(String s) {
char[] array = s.toCharArray();
boolean head = true;
boolean negative = false;
String reverse = "";
if(array[0] == '-') negative = true;
for(int i = array.length - 1, j = 0; i >= 0; i--,j++) {
if(negative) {
if(array[i] == '0' && head) continue;
if(i == 0) break;
reverse += array[i];
head = false;
}
else {
if(array[i] == '0' && head) continue;
reverse += array[i];
head = false;
}
}
if(negative) reverse = '-' + reverse;
return reverse;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
reverse r =new reverse();
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.print(r.reverse(num));
sc.close();
}
}
总结与反思
String str1 = "" + x;
将整型变量转换成字符串类型;char[] array = s.toCharArray();
将字符串转换为字符型数组;if(num>Integer.MAX_VALUE) System.out.println("num上溢出");
if(num<Integer.MIN_VALUE) System.out.println("num下溢出");
判断整型数据是否溢出;