最先想到的当然是for循环了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public static void main(String[] args) { long time1 = System.currentTimeMillis(); System.out.println("当前时间为"+time1); int n = 0; int n1, n5, n10, n50; for (n1 = 0; n1 < 100; n1++) { for (n5 = 0; n5 < 20; n5++) { for (n10 = 0; n10 < 10; n10++) { for (n50 = 0; n50 < 2; n50++) { if (n1 * 1 + n5 * 5 + n10 * 10 + n50 * 50 == 100) { n++; System.out.println("1块的:" + n1 + "张 5块的: " + n5 + "张 10块的 :" + n10 + "张 50块的:" + n50 + "张"); } } } } } long time2 = System.currentTimeMillis(); System.out.println("结束时间为"+time2); long time = time2 - time1; System.out.println(n + " 耗费时间为 " + time); }
|
很容易得出结果154.但是耗费时间为 1501038954420 - 1501038954413 =7;
虽然时间耗费不是很多,但是通过打印信息可以看出来,50为2的时候只有一种情况,却空跑了很多空循环。