题目:
将一整数逆序后放入一数组中(要求递归实现)
实现方法:
1、递归(含无效字符)
2、字符操作(数组中含无效字符)
3、字符操作(数组中不含无效字符)
Java实现源代码(方法 1):
public class zhengshu {
// 将一整数逆序后放入一数组中(要求递归实现)
public void reverse(StringBuffer result, int num) {
if (num != 0) {
result.append(num % 10);
reverse(result, num / 10);
}
}
public static void main(String[] args) {
StringBuffer result = new StringBuffer();
new zhengshu().reverse(result, 1024);
System.out.println(result);
}
}
PS:数组中存在无效字符(例如:0)
Java实现源代码(方法 2):
import java.util.Scanner;
public class tter {
// 将一整数逆序后放入一数组中
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.next();
int[] resu = new int[str.length()];
int temp, i = 0;
int res = Integer.parseInt(str);
for (i = 0; i < str.length(); i++) {
temp = res % 10;
resu[i] = temp;
res = res / 10;
}
for (i = 0; i < str.length(); i++) {
if(resu[i]==0){
continue;
}
System.out.print(resu[i]);
}
}
}
PS:数组中存储了无效字符(例如:0)
Java实现源代码(方法 3):
import java.util.Scanner;
public class zhengshu {
// 将一整数逆序后放入一数组中
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String strOld = in.next();
int[] resu = new int[strOld.length()];
int temp, i = 0, j = 0;
for (j = strOld.length() - 1; j >= 0; j--) { // 处理末尾是0的情况,实现数组中存储首位非0的数值
if (!"0".equals(strOld.substring(j, j + 1)))
break;
}
String strNew = strOld.substring(0, j + 1);
int res = Integer.parseInt(strNew);
for (i = 0; i < strNew.length(); i++) {
temp = res % 10;
resu[i] = temp;
res = res / 10;
}
for (i = 0; i < strNew.length(); i++) {
if(resu[i]==0){
continue;
}
System.out.print(resu[i]);
}
}
}
PS:数组中未存储无效字符(例如:0)
读者注意区分 3 者的差别,希望有所体会。