Reverse Integer

来源:互联网 发布:dota2 mac怎么全屏 编辑:程序博客网 时间:2024/04/30 05:38

Reverse digits of an integer.

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

click to show spoilers.

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

本人给出的代码:

public class ReverseOne {
public int reverse(int x) {
int b[] = { 2, 1, 4, 7, 4, 8, 3, 6, 4, 7 };
int c[] = { 2, 1, 4, 7, 4, 8, 3, 6, 4, 8 };
int m = x;
if (x < 0) {
m = -x;
}
if (x == 0) {
return 0;
}
String aString = new Integer(m).toString();
int l = aString.length();
int a[] = new int[l];
int i = 0;
while (m > 0) {
a[i++] = m % 10;
m /= 10;
}
int sum = 0;
if (l==10) {
if (x>0) {
boolean flag=false;
for (int j = 0; j < a.length; j++) {
if (a[j]>b[j]) {
flag=false;
break;
}else if(a[j]==b[j]){
continue;
}else {
flag=true;
break;
}
}
if (flag) {
for (int j2 = 0; j2 < a.length; j2++) {
sum *= 10;
sum += a[j2];
}
return sum;
}else {
return 0;
}

}else {
boolean flag2=false;
for (int j = 0; j < a.length; j++) {
if (a[j]>c[j]) {
flag2=false;
break;
}else if(a[j]==c[j]){
continue ;
}else {
flag2=true;
break;
}
}
if (flag2) {
for (int j2 = 0; j2 < a.length; j2++) {
sum *= 10;
sum += a[j2];
}
return -sum;
}else {
return 0;
}
}
}
for (int j = 0; j < a.length; j++) {
sum *= 10;
sum += a[j];
}
if (x < 0) {
return -sum;
} else {
return sum;
}
}
}

0 0
原创粉丝点击