算法導論 31.1-13 將二進制整數轉化爲相應的十進制表示

31.1-13 寫出一個高效算法,用於將β位二進制整數轉化爲相應的十進制表示。證明:如果長度至多爲β的整數的乘法或除法運算所需時間爲M(β),則執行二進制到十進制轉換所需時間爲θ(M(β)lgβ)。(提示:應用分治法,分別使用獨立的遞歸計算結果的前段和後段)

  public static int convertBin2DecQuick(byte[] bits) {
    if(bits.length != 32) {
      throw new IllegalArgumentException("Integer should be 32 bits");
    }
    int negative = 0;
    if(bits[31]==1) { // negative integer
      negative = Integer.MIN_VALUE;   // -2^31
    }
    int decimal = convert2DecimalQuick(bits, 0, 30);
    decimal = negative + decimal;
    return decimal;
  }
  public static int convert2DecimalQuick(byte[] bits, int start, int end) {
    int value = 0;
    if(start < end) {
      int mid = (start+end) >>> 1;
      int left = convert2DecimalQuick(bits, start, mid);
      int right = convert2DecimalQuick(bits, mid+1, end);
      value = left + right;    
    }
    else if(start == end) {
      if(bits[start] == 1) {
        value = 1 << start;  // 2^start
      }
    }
    return value;
  }

  //Let (bk, bk-1,...,b1,b0) be the binary representation of integer n
  public static byte[] convert2Binary(int n) {
    byte[] b = new byte[32];  // integer is 32 bits
    if(n == 0) {
      return b;
    }
    if(n == 1) {
      b[0] =1;
      return b;
    }
    int i = 0;
    while(n != 0) {
      b[i] = (byte)( n & 1);
      n = n >>> 1;  //move right without sign
      i++;
    }
    return b;
  }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章