Java基础算法集50题

时间:2023-02-17 12:05:05


1,有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? 

分析:

        月份:1    2    3   4   5   6    7

兔子数量:1    1    2   3   5   8    13

可以发现规律:连续两个月兔子数量之和为第三个月的兔子数量

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class TestRabbit {
private static int month = 15;
private static Map<Integer, Integer> map = new HashMap<Integer, Integer>();
public static void main(String[] args) {
map.put(1, 1);
map.put(2, 1);
// 从第三个月开始计算
for (int i = 3; i <= month; i++) {
map.put(i, getNumsByMonth(i));
}
Set<Integer> set = map.keySet();
for (Integer key : set) {
System.out.println("第" + key + "月的兔子数是" + map.get(key));
}
}

private static int getNumsByMonth(int monthNo) {
Integer month_Previous_one = map.get(monthNo - 1);
Integer month_Previous_two = map.get(monthNo - 2);
return month_Previous_one + month_Previous_two;
}
}

---------------------------------------------------------------------------------------------------------------------------------------------------------------

2,打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身

public class GetDaffodilNumber {
public static void main(String[] args) {
for (int i = 100; i <= 999; i++) {
if (getDaffodilNumber(i) != 0) {
System.out.println(i);
}
}
}


private static int getDaffodilNumber(int num) {
String numStr = num + "";
String firstNum = numStr.substring(0, 1);
String secNum = numStr.substring(1, 2);
String thirtNum = numStr.substring(2, 3);
if (num == (Math.pow(Integer.parseInt(firstNum), 3) + Math.pow(Integer.parseInt(secNum), 3)
+ Math.pow(Integer.parseInt(thirtNum), 3))) {
return num;
}
return 0;
}
}