算法导论 31.1-13 将二进制整数转化为相应的十进制表示

本文介绍了一种高效的算法,用于将32位二进制整数快速转换为十进制表示。该算法利用了分治策略,通过递归地计算二进制数的高位和低位部分,最终实现整体的转换。文章还提供了具体的Java实现代码,并讨论了算法的时间复杂度。

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;
  }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值