[LeetCode]Add Binary

题目:给定两个二进制数字字符串A、B,计算出A+B并返回和值的字符串

算法一:最原始的办法,模拟二进制的运算,因考虑到给定的二进制字符串很长,所以使用Java的BigInteger实现

import java.math.BigInteger;

public class Solution {
    /**
     * Convert binary number to BigInteger.
     * @param binary
     * @return
     */
    public BigInteger convertBinaryToBigInteger(String binary) {
        BigInteger factor  = BigInteger.ONE;
        BigInteger convert = BigInteger.ZERO;
        
        int length = binary.length();
        for (int i=length-1; i>=0; --i) {
            long num = (long)(binary.charAt(i)-'0');
            convert = convert.add(factor.multiply(BigInteger.valueOf(num)));
            
            factor = factor.shiftLeft(1);
        }

        return convert;
    }
    
    /**
     * Convert BigInteger to binary number.
     * @param c
     * @return
     */
    public String convertBigIntegerToBinary(BigInteger c) {
        if (c.equals(BigInteger.ZERO)) {
            return "0";
        }
        
        String res = new String();
        BigInteger factor = BigInteger.valueOf(2L);
        while (!c.equals(BigInteger.ZERO)) {
            res += c.mod(factor).toString();
            c = c.divide(factor);
        }
        
        return new StringBuffer(res).reverse().toString(); 
    }
    
    /**
     * Add Two given binary number and return the binary number of their sum.
     * @param a
     * @param b
     * @return
     */
    public String addBinary(String a, String b) {
        BigInteger aBigInteger = convertBinaryToBigInteger(a);
        BigInteger bBigInteger = convertBinaryToBigInteger(b);
        
        return convertBigIntegerToBinary(aBigInteger.add(bBigInteger));
    }
}

算法二:利用异或运算,这种方法更加优雅

public String addBinary(String a, String b) {
        String convert = new String();
        char[] aArray = a.toCharArray();
        char[] bArray = b.toCharArray();
        
        int aByte  = 0;
        int bByte  = 0;
        int carry  = 0;
        int aIndex = aArray.length - 1;
        int bIndex = bArray.length - 1;
        while (aIndex>-1 || bIndex>-1 || carry>0) {
            aByte = aIndex > -1 ? Character.getNumericValue(aArray[aIndex--]) : 0;
            bByte = bIndex > -1 ? Character.getNumericValue(bArray[bIndex--]) : 0;
            
            convert += String.valueOf(aByte ^ bByte ^ carry);
            carry = (aByte + bByte + carry) > 1 ? 1 : 0;
        }// end of while
        
        return new StringBuffer(convert).reverse().toString();
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值