leetcode: add-binary

给定两个二进制字符串,返回它们的和(也是一个二进制字符串)。

举例:
a = "11"
b = "1"
返回 "100".

解题思路:

  1. 这题比较简单,所以我使用的是比较暴力的算法
  2. 将两个字符串转换成整型数组的形式
  3. 对两个数组进行相加,注意进位
  4. 将求得的和数组转换成字符串返回

代码如下:

    public String addBinary(String a, String b) {

        int len1 = a.length();
        int len2 = b.length();

        int maxlen = len1 > len2 ? len1 : len2;

        int [] m = new int [maxlen ];
        int [] n = new int [maxlen ];

	// 将字符串转换成数组
        int index1 = 0;
        while(len1 < maxlen){
            m[index1++] = 0;
            len1++;
        }

        for(int i = 0; i < a.length(); i++){
            m[index1++] = (int)(a.charAt(i) - 48);
        }

        int index2 = 0;
        while(len2 < maxlen){
            n[index2++] = 0;
            len2++;
        }

        for(int i = 0; i < b.length(); i++){
            n[index2++] = (int)(b.charAt(i) - 48);
        }

        return add(m,n);

    }

    // 对数组进行求和
    private String add(int [] m, int [] n){
        int [] res = new int [m.length + 1];

        int index = res.length - 1;
        int count = 0;
        for(int i = m.length - 1; i >= 0; i--){
            count += m[i] + n[i];
	
	    // 利用 count 处理进位
            if(count == 0){
                res[index--] = 0;
                count = 0;
            }
            else if(count == 1){
                res[index--] = 1;
                count = 0;
            }
            else if(count == 2){
                res[index--] = 0;
                count = 1;
            }
            else if(count == 3){
                res[index--] = 1;
                count = 1;
            }
        }
	
	// 处理和数组的第一位问题
        if(count == 1){
            res[index] = count;
        }else{
            res =  Arrays.copyOfRange(res,1,res.length);
        }

	// 将数组转换为字符串,并返回
        String rs = "";
        for(int i = 0; i < res.length; i++){
            rs += res[i];
        }
        return rs;
    }

转载于:https://my.oschina.net/happywe/blog/3073711

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值