下面是两个具有两个不同功能的递归代码。
[1]我使用递归代码检查回文是这样的:
import java.util.Scanner;
public class CheckPalindromeRecursion {
public static boolean recursion(String pal) {
if (pal.length() == 0 || pal.length() == 1) {
return true;
} else if (pal.charAt(0) == pal.charAt(pal.length() - 1)) {
return recursion(pal.substring(1, pal.length() - 1));
}
return false;
}
public static void main(String[] args) {
System.out.println("Enter the String for check:");
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
if(recursion(str))
System.out.println(str + " is a palindrome");
else
System.out.println(str + " is not a palindrome");
scan.close();
}}
[2]我使用递归代码反转一个数字是这样的:
import java.util.Scanner;
public class ReverseNumberRecursion {
public static void reverse(int numb) {
if (numb < 10) {
System.out.print(numb);
return;
} else {
System.out.print(numb % 10);
reverse(numb/10);
}
}
public static void main(String[] args) {
System.out.print("The number you want to reverse is: ");
Scanner in = new Scanner(System.in);
int numb = in.nextInt();
in.close();
System.out.print("The reversed number is: ");
reverse(numb);
}}
为什么我必须在 - [1]:中使用返回,但在 - [2]:中不需要使用返回? return recursion(pal.substring(1, pal.length() - 1)); reverse(numb/10);
MMMHUHU
相关分类