Skip to content

Latest commit

 

History

History
85 lines (70 loc) · 1.86 KB

查表法.md

File metadata and controls

85 lines (70 loc) · 1.86 KB

查表法

使用時機

  • 如果數據出現了對應關係,而且對應關係的一方是有序的數字編號,並作為角標使用。這時就必須要想到數組的使用,並將這些數據存儲到數組中。 根據運算的結果作為角標直接去查數組中對應的元素即可。

這種方式稱為查表法

Example:

日期查表

public class ArraySearch {

  public static void main(String[] args) {
    String week = getWeek(2); //數組查表法
    System.out.println(week);
  }
    
  private static String getWeek(int num) {
    //定義一個對應關係表
    String[] weeks = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
    /*
    一會查表查到比較的數據
    數據一多,就先存儲起來,再進行操作。
    所以定義一個數組作為臨時容器。
    */
    		
    		
    return arr[num - 1];//通過索引獲取表中元素
  }
}

進制轉換

public class  ArraySearch_2{
  public static void main(String[] args) {
    toBinary(-6);
    // toOctal(26);
    // toHex(26);
    System.out.println(Integer.toBinaryString(-6));
}
    
//二進制
public static void toBinary(int num) {
  trans(num,1,1);
}
//八進制
public static void toOctal(int num) {
  trans(num,7,3);
}
//十六進制
public static void toHex(int num) {
  trans(num,15,4);
}
    
public static void trans(int num,int base,int offset) {

  if(num==0) {
    System.out.println("0");
    return;
  }

  char[] chs = {'0','1','2','3',
                '4','5','6','7',
                '8','9','A','B',
                'C','D','E','F'};

  char[] arr = new char[32];
  int pos = arr.length;

  while(num!=0) {
    int temp = num & base;
    arr[--pos] = chs[temp];
    num  = num >>> offset;
  }

  for(int x=pos ;x<arr.length; x++) {
    System.out.print(arr[x]);
  }

  System.out.println();    
  }
}