算法 发表于 2023-04-15 更新于 2023-07-10 😀 1到100之间的偶数之和123456789101112131415//方法一 var sum =0; for (int i = 2; i <= 100; i+=2) { sum+=i; } System.out.println(sum);//方法二 var s=0; var a=1; var b=100; for (; a <= b; a++) { s+=a%2==0?a:0; } System.out.println(s); 逢七过1234567891011121314//方法一 for (int i = 0; i < 100; i++) { if (i % 10 == 7 || i / 10 % 10 == 7 || i % 7 == 0) { System.out.println("过"); continue; } System.out.println(i); }//方法二 for (int i = 0; i < 100; i++) { String d = (i % 10 == 7 || i / 10 % 10 == 7 || i % 7 == 0 ? "过" : String.valueOf(i)); System.out.println(d); } 求和123456List<Integer> list = List.of(1, 2, 3, 4, 5, 6); var sm =0; for (int i = 0; i < list.size(); i++) { sm+=list.get(i); } System.out.println(sm); 二分半查找1234567891011121314151617181920212223@Test public void test(){ int[] arr = {1, 2, 3, 4, 5, 6, 7}; System.out.println(bina(arr, 4));}private static int bina(int[]arr,int number) { var min=0; var max=arr.length-1; while (true) { if (min > max) { return -1; } int mid =(min+max)/2; if (arr[mid] > number) { max=mid-1; } else if (arr[mid] < number) { min = mid + 1; } else { return mid; } }} 冒泡排序12345678910111213141516@Test public void test1(){ int[] arr = {2, 5, 3, 4, 1}; for (int i = 0; i < arr.length-1; i++) { for (int j = 0; j < arr.length-1-i; j++) { if (arr[j] > arr[j+1]) { int temp =arr[j]; arr[j] = arr[j + 1]; arr[j+1]=temp; } } } for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]+" "); } } 选择排序123456789101112131415161718@Testpublic void test2(){ int[] arr = {2, 3, 1, 5, 4}; for (int i = 0; i < arr.length-1; i++) { for (int j = i+1; j < arr.length; j++) { if (arr[i] > arr[j]) { int temp =arr[i]; arr[i] = arr[j]; arr[j]=temp; } } } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }}