【问题标题】:Adding two large binary numbers添加两个大的二进制数
【发布时间】:2012-03-23 18:32:54
【问题描述】:

我正在尝试添加两个更大的二进制数(即位数大于 31),但由于获得NumberFormatException 而被卡住。下面是抛出异常的行-

Integer.parseInt(binaryNo, 2);

我的想法是先将两个二进制数转换为integer,然后将integer 加在一起,然后使用Integer.toBinaryString(integerSum) 转换回二进制数。但它不适用于位数大于 31 的二进制数,因为会发生整数溢出。请告诉我可以以优化方式(最短时间)执行大二进制数加法的任何方式。谢谢。

【问题讨论】:

    标签: java binary


    【解决方案1】:

    java.math.BigInteger。构造它:

    public BigInteger(String val,
                      int radix)
    

    在这种情况下,您的基数是 2。请注意,每个 BigInteger 都是不可变的,因此您执行算术的方式略有不同:

    BigInteger i = new BigInteger(...);
    Biginteger j = new BigInteger(...);
    
    BigInteger sum = i.add(j); // neither i nor j are modified
    

    【讨论】:

      【解决方案2】:

      您可以改用java.math.BigInteger。它具有任意精度,可以处理任意基数(在您使用二进制文件的情况下,基数为 2)并且应该得到相当好的优化。

      【讨论】:

        【解决方案3】:

        考虑使用java.math.BigInteger 类:

        BigInteger first=new BigInteger(binaryNo1, 2);
        BigInteger second=new BigInteger(binaryNo2, 2);
        
        BigInteger result=first.add(second);
        String binResult=result.toString(2);
        

        【讨论】:

          猜你喜欢
          • 2017-03-14
          • 1970-01-01
          • 1970-01-01
          • 2018-09-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-10
          • 2018-06-29
          相关资源
          最近更新 更多