题目1:用递归实现字符串倒转
题目2:一个有n级的台阶,一次可以走1级、2级或3级,问走完n级台阶有多少种走法。
题目3:输入年月日,计算该日期是这一年的第几天。
package question;
/**
* @Author: WYF
* @Description: 用递归实现字符串倒转
* @Create: 2020/4/23 23:02
* @Version: 1.0
*/
public class StringReverse {
public static String reverse(String s){
if (s == null || s.length()==1) {
return s;
}
return reverse(s.substring(1))+s.charAt(0);
}
public static void main(String[] args) {
System.out.println(reverse("hello"));
}
}
学习与思考:Sting类的Substring()方法,用来分割字符串的
用法1:Substring(int start); 表示分割从索引strat开始的数据,索引从0开始,区间[start,末尾]
用法2:Substring(int start,int end); 表示分割从索引strat开始的数据,到end前一位结束
package question;
/**
* @Author: WYF
* @Description: 一个有n级的台阶,一次可以走1级、2级或3级,问走完n级台阶有多少种走法。
* @Create: 2020/4/23 23:08
* @Version: 1.0
*/
public class GoStepts {
public static int countWays(int x) {
int[] arr = new int[x + 1];
arr[1] = 1;
arr[2] = 2;
arr[3] = 4;
for (int i = 4; i <= x; i++) {
arr[i] = arr[i - 1] + arr[i - 2] + arr[i-3];
}
return arr[x];
}
public static void main(String[] args) {
System.out.println(countWays(5)); // 13
}
}
也可以采用递归的方式,这里用空间换时间了
package question;
import java.util.Scanner;
/**
* @Author: WYF
* @Description: 输入年月日,计算该日期是这一年的第几天。
* @Create: 2020/4/23 23:38
* @Version: 1.0
*/
public class TheDay {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入年月日(1980 11 28): ");
int year = sc.nextInt();
int month = sc.nextInt();
int date = sc.nextInt();
int[] data;
//判断是不是润年
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {//是
data = new int[]{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
} else {
data = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
}
int sum = date;
for (int i = 0; i < month - 1; i++) {
sum += data[i];
}
System.out.println(sum);
}
}
润年的判断:四年一润、百年不润、四百又润