繁体   English   中英

二进制到十进制递归方法

[英]Binary to Decimal Recursive Method

我试图找出通过递归从二进制转换为十进制的方法。 根据纸上的计算,我的方法构造如下。 如果二进制为“ 1100”(十进制为12),则

 /*1100 ---> 12
      (1)*2 + "100"
    (2 + 1)*2 + "00"
      (6 + 0)*2 + "0"
         (12 + 0) + "" */

我已经坚持了一段时间。 这是我想出的。 我感谢任何想法。 谢谢。

int binary2decimal(String b)
{
    if ("".equals(b))  //base case
        return 0;
    else               //general case
    {   if (b.length() == 1)
            return (b.charAt(0) - '0') + binary2decimal(b.substring(1));
        else
            return (b.charAt(0) - '0')*2 + binary2decimal(b.substring(1));
    }
}
int binary2decimal(String b)
{
        int dec = 0;
        int len = b.length();
        if (len >= 1)
        {
            dec = (b.charAt(len-1) - '0');
            if (len > 1) dec += binary2decimal(b.substring(0,len-1))<<1;
        }
        return dec;
}

重点是向后递归 (即从LSB到MSB)

编辑 binary2decimal(b.substring(0,len-2))需要上升到len-1 ,已修复

这应该工作:

class binary {
    public static void main(String[] args)
    {
        int myBinary = binary2decimal("1100");
        System.out.println(myBinary); 
       //System.out.println(binary2decimal("1100")); 
    }
static int binary2decimal(String b) {
    int len = b.length();
    if (len == 0) return 0;
    String now = b.substring(0,1);
    String later = b.substring(1);
    return Integer.parseInt(now) * (int)Math.pow(2, len-1) + binary2decimal(later);     
  }
}

输出:

OUTPUT : 12

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM