最基本的,斐波那契数列,阶乘(0,1的阶乘均为1)
返回字母“x”第一次出现的位置
使用递归编写一个函数,读取一个字符串,返回字母“x”第一次出现的位置。例如,字符串
"abcdefghijklmnopqrstuvwxyz"中“x”第一次出现在索引 23 处。为简单起见,假设字符
串一定至少有一个“x”
public class FindFirstPos {public static void main(String[] args) {String info = "abcdefghijklmnopqrstuvwxyz";System.out.println(FindFirstCharPos(info, 'x'));}public static int FindFirstCharPos(String info, char c){if(info.charAt(0) == c){return 0;}else{return 1 + FindFirstCharPos(info.substring(1), c);}}
}
字符串数组长度求和
使用递归编写一个函数,读取一个字符串数组,返回所有字符串的字母数之和。
如果输入数组是[“ab”, “c”, “def”, “ghij”],那么因为一共有 10 个字母,
所以函数应该返回 10
public class StringSum2 {public static void main(String[] args) {String[] arr = {"ab", "c", "world","def", "ghij","hello"};System.out.println(sumStr(arr, arr.length-1));}public static int sumStr(String[] arr, int n){if(n == 0){return arr[n].length();}else{return arr[n].length() + sumStr(arr, n - 1);}}
}
public class PathNum {public static void main(String[] args) {int[][] arr = new int[3][7];System.out.println(pathNum(arr, 0, 0));}public static int pathNum(int[][] arr, int i, int j) {if(i == arr.length - 1 || j == arr[0].length - 1){return 1;}else {return pathNum(arr, i + 1, j) + pathNum(arr, i, j + 1);}}
}
判断回文
public class Huiwen {public static void main(String[] args) {String info = "abcczba";System.out.println(isHuiWen(info));}public static boolean isHuiWen(String info){if(info.length() == 1){return true;}else if(info.length() == 2){return info.charAt(0) == info.charAt(1);}else{return (info.charAt(0) == info.charAt(info.length() - 1)) && isHuiWen(info.substring(1,info.length()-1));}}
}