1.数组逆序
import java.util.*; public class Main { public static void main(String[] args) { int arr[] = {0,57,7,5,1}; int N = arr.length; for(int i=0;i<N/2;i++){ int tmp = arr[i]; arr[i] = arr[N-i-1]; arr[N-i-1] = tmp; } System.out.println(Arrays.toString(arr)); } }
2.判断是否是素数
public static boolean isPrime(int a) { if (a < 2){ return false; } else { for (int i = 2; i <= Math.sqrt(a); i++){ if (a % i == 0) return false; } } return true; }
3.开根号
/* * 牛顿迭代法 开方 2 = 根号2 */ public static double sqrt(double num){ if(num<0){ return Double.NaN; } double err = 1e-15; double t = num; while(Math.abs(t-num/t)> err*t){ t = (t+num/t)/2.0; } return t; }
4. 二分查找,注意查询之前要排序
public static void main(String[] args) { int arr[] = {0,57,7,5,1}; Arrays.sort(arr); System.out.println(Arrays.toString(arr)); System.out.println(rank(7,arr)); } public static int rank(int key,int[] arr){ return rank(key,arr, 0, arr.length-1); } public static int rank(int key,int [] arr, int lo,int hi){ //return 0; if(lo>hi){ return -1; } int mid = lo+(hi-lo)/2; if(arr[mid]>key){ return rank(key,arr,lo,mid-1); }else if(arr[mid]<key){ return rank(key,arr,mid+1,hi); }else{ return mid; } //return hi; }
4.判断 回文数
/** * 判断是不是回文数 * @param str * @return */ public static boolean isBack(String str){ int N = str.length(); for(int i=0;i<N/2;i++){ if(str.charAt(i)!=str.charAt(N-i-1)){ return false; } } return true; }