关于数字的逆置
Talk is cheap, I’ll show you the code.
**
代码:
**
public static void main(String[] args) throws Exception { //主函数
//StringBuilder是可变字符串,原串可以发生变化,使用起来比较方便,因此此处使用StringBuilder
//使用字符串的反转来实现数串的反转,从而实现数字的反转
StringBuilder sb1 = null;
StringBuilder sb2 = null;
Scanner sc1 = new Scanner(System.in);
System.out.println("请输入数串:");
String str = sc1.next();
sb1 = new StringBuilder(str);
sb2 = new StringBuilder(str);
//reverse(StringBuilder sb),只能反转正数串
System.out.println("反转前为" + sb1);
sb1 = reverse(sb1);
System.out.println("反转后为" + sb1);
System.out.println("===============================");
//根据第一个字符判断输入的是正数还是负数
//正数第2个参数为0,负数第2个参数为1
if(sb2.charAt(0)=='-'){
System.out.println("反转前为" + sb2);
sb2 = reverse(sb2,1,str.length()-1);
System.out.println("反转后为" + sb2);
}else{
System.out.println("反转前为" + sb2);
sb2 = reverse(sb2,0,str.length()-1);
System.out.println("反转后为" + sb2);
}
System.out.println("===============================");
Scanner sc2 = new Scanner(System.in);
System.out.println("请输入int数字:");
int number=sc2.nextInt();
System.out.println(number+"反转后为"+ reverse(number));
System.out.println("===============================");
System.out.print(number+"反转后为");
reverse1(number);
}
public static StringBuilder reverse(StringBuilder sb) { //反转数串的函数,反转整个数串
//函数思想主要是交换对称位置的数字
//循环的次数看数串的长度,奇数时中间的那个数不用交换,偶数时交换
for (int i = 0; i < sb.length() / 2; i++) {
//头部和尾部指的是未发生交换的数串的头尾
char temp, head, tail;
head = sb.charAt(i);//根据索引获取头部数字
tail = sb.charAt(sb.length() - 1 - i);/根据索引/获取尾部数字
//交换对称位置的数字
temp = head;
head = tail;
tail = temp;
//重新设置对称位置的数字
sb.setCharAt(i, head);//根据索引设置头部数字
sb.setCharAt(sb.length() - 1 - i, tail);//根据索引设置尾部数字
}
return sb;
}
public static StringBuilder reverse(StringBuilder sb,int i,int j) throws Exception {
//throws Exception为了抛出索引越界异常
//反转数串指定部分,
//可用于反转整数或者负数,正数第一个参数设置为0,负数第一个参数设置为1,第二个参数为数串的长度-1
if (i<j){//交换两头
//头部和尾部指的是未发生交换的数串的头尾
char temp, head, tail;
head = sb.charAt(i);//根据索引获取头部数字
tail = sb.charAt(sb.length() - 1 - i);/根据索引/获取尾部数字
//交换对称位置的数字
temp = head;
head = tail;
tail = temp;
//重新设置对称位置的数字
sb.setCharAt(i, head);//根据索引设置头部数字
sb.setCharAt(sb.length() - 1 - i, tail);//根据索引设置尾部数字
reverse(sb,i+1,j-1);//递归调用,减而治之
return sb;
}else {
//包含两种情况
//两头重合,不用交换,直接返回
//尾小于头,也不用交换,直接返回
return sb;
}
}
public static int reverse(int a){//用于反转整数
int inverse=0;
int digit;//末尾的个位数
while(Math.abs(a)>0){
digit=a%10;//末尾的个位数
inverse=inverse*10+digit;
//通过这个while循环
//每个数字乘10的次数为所在位数与从左往右第一个非0位数的差
//如007892,7是第一位,8是第2位,9是第3位,2是第4位,8*10+9*10*10+2*10*10*10
a/=10;//控制循环结束
}
return inverse;
}
public static void reverse1(int a){
int digit;//末尾的个位数
System.out.print("-");
while(Math.abs(a)>0){
digit=Math.abs(a%10);
System.out.print(digit);
a/=10;
}
}
**
测试结果:
**