您的位置:首页 > 其它

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

2014-11-22 23:34 435 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: