算法之路——POJ刷题(Java,持续更新中)
先拿一些水题来练手了
1.POJ1000
简单的计算a+b,就不多说了
import java.util.Scanner; /** * Created by mxcsky on 2015/1/25. */ public class POJ1000 { public static void main(String[] args){ Scanner in = new Scanner(System.in); int a = in.nextInt(); int b = in.nextInt(); System.out.println(a + b); } }
2.POJ1003
给定长度c,求满足1/2 + 1/3 + 1/4 + ... + 1/(n + 1) >= c所需要的最小正整数n,这里需要注意的是,当c <= 1/2时,都只需1 card(s),另外判断浮点数是否为0.00时,我使用的是
if (m < 0.00001)
若使用
if (m == 0.00)
也可以通过POJ系统,不知道这里是否正确,希望读者能够指正
import java.util.Scanner; /** * Created by mxcsky on 2015/1/25. */ public class POJ1003 { public static void main(String[] args){ Scanner in = new Scanner(System.in); while(true) { double m = in.nextDouble(); double sum = 0.0; int i = 1; if (m < 0.00001) { System.exit(0); } if (m <= 0.5) { System.out.println("1 card(s)"); } else { while (sum < m) { i++; sum = sum + 1.0 / i; } System.out.println((i - 1) + " card(s)"); } } } }
3.POJ1004
求12个月的平均余额,输出以$开头,精确到美分(即小数点第二位)
import java.util.Scanner; /** * Created by mxcsky on 2015/1/25. */ public class POJ1004 { public static void main(String[] args){ Scanner in = new Scanner(System.in); double sum = 0.0; for (int i = 0; i < 12; i++){ sum = sum + in.nextDouble(); } System.out.printf("$%.2f", sum/12); } }
4.POJ1207
根据给定的算法得出循环数,注意输入有可能不是从小到大,所以需要排序,但是输出时要按照原顺序输出,例如输入200 100,输出200 100 125
import java.util.Scanner; /** * Created by mxcsky on 2015/1/25. */ public class POJ1207 { public static void main(String[] args){ Scanner in = new Scanner(System.in); String str = new String(); while (in.hasNext()){ str = in.nextLine(); String[] array = str.split(" "); int i = Integer.parseInt(array[0]); int j = Integer.parseInt(array[1]); int t = 0; int signal = 0; int num = 0; int max = 0; int n = 0; if (i > j){ t = i; i = j; j = t; signal = 1; } else { signal = 0; } for(int temp = i; temp <= j; temp++){ n = temp; while (true){ if (n == 1){ num++; break; } else { if (n % 2 == 1){ n = 3 * n + 1; num++; } else { n = n / 2; num++; } } } if (max < num){ max = num; } num = 0; } if (signal == 0){ System.out.println(i+" "+j+" "+max); } else { System.out.println(j+" "+i+" "+max); } } } }