问题:将一个数字反转,如:12345,进行反转为54321,;-12345,反转为-54321;
package ReverseInteger;
import org.junit.Test;
/*
* 将一个数字反转,要判断数是大于0还是小于0
* 然后对数字进行反转,利用while循环
*/
public class TestReverseInteger {
@Test
public void fun3() {
int a = -12345;
int b = reverseInteger1(a);
System.out.println(b);
}
public int reverseInteger(int a){//数字反转的算法
int sum = 0;
while (a != 0) {
sum = sum * 10 + a % 10;
a = a / 10;
}
return sum;
}
//这个是分部计算的思路
public int reverseInteger1(int a) {
int sum = 0;
if (a > 0){
while (a > 0){
sum = sum * 10 + a % 10;
a = a / 10;
}
return sum;
}
else if (a < 0) {
int b = -a;
while (b > 0){
sum = sum * 10 + b%10;
b = b / 10;
}
return -sum;
}
else {
return sum;
}
}
}