最近看到一个题,键盘输入一个数number,输出从1到number的所有奇数和偶数,有好几种算法
一、
取余+集合算法输出:
1 package com.company; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 import java.util.Scanner; 8 9 public class Test3 { 10 11 private int total; 12 private int even = 0; 13 private int odd = 0; 14 15 public void getNumber(int number) { 16 Map map = new HashMap(); 17 List list1 = new ArrayList(); 18 List list2 = new ArrayList(); 19 20 for (int i = 0; i <= number; i++) { 21 if (i % 2 == 0) { 22 //even = even + i; 23 list1.add(i); 24 } else { 25 //odd = odd + i; 26 list2.add(i); 27 } 28 } 29 System.out.println("1-" + number + "范围之间的偶数有:" + list1.toString() + "偶数和为:" + even); 30 System.out.println("1-" + number + "范围之间的奇数有:" + list2.toString() + "奇数和为:" + odd); 31 32 } 33 34 public static void main(String[] args) { 35 Scanner sc = new Scanner(System.in); 36 System.out.println("请输入一个整数:"); 37 int number = sc.nextInt(); 38 long starttime = System.currentTimeMillis(); 39 Test3 t = new Test3(); 40 t.getNumber(number); 41 long endtime = System.currentTimeMillis(); 42 System.out.println("运行时间:" + (endtime - starttime) + "ms"); 43 } 44 }
以上这种算法在数据为10万情况下,测得运行时间为852ms
二、位运算+集合
package com.company; import java.util.ArrayList; import java.util.Scanner; public class Test4 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入一个数:"); int number=sc.nextInt(); ArrayList list1 = new ArrayList(); ArrayList list2 = new ArrayList(); //int[] a =new int[number]; long starttime = System.currentTimeMillis(); for (int i = 0; i < number; i++) { if((i&1)==1){ list1.add(i); }else{ list2.add(i); } } System.out.println("奇数!"+list1.toString()+"\n"+"偶数!"+list2.toString()); long endtime = System.currentTimeMillis(); System.out.println("运行时间:"+(endtime-starttime)+"ms"); } }
以上这种算法在数据为10万情况下,测得运行时间为714ms
三、StringBulider+单层for循环
package com.company; import java.util.Scanner; public class Test5 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入一个数:"); int number = sc.nextInt(); StringBuilder s1 = new StringBuilder(); StringBuilder s2 = new StringBuilder(); long starttime = System.currentTimeMillis(); for (int i = 0; i < number; i += 2) { s1.append(i).append(","); s2.append(i+1).append(","); } System.out.println("奇数是:"+s1); System.out.println("偶数是:"+s2); long endtime = System.currentTimeMillis(); System.out.println("运行时间:"+(endtime-starttime)+"ms"); } }
以上这种算法在数据为10万情况下,测得运行时间为423ms
可以看出 如果只是输出,还是字符串拼接效率最高。
--------本人初学者,欢迎评论区大佬留言-------------
原文地址:https://www.cnblogs.com/run-forrest-gump/p/12547499.html
时间: 2024-10-11 13:26:47