Add Binary leetcode

Add Binary

Apr 2 '12

5763 / 16556

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".


我的丑陋的

public class Solution {
    public String addBinary(String a, String b) {

        if(a==null||b==null) return null;
        
        int la = a.length(),lb = b.length();
        
        int add = 0;
        int i = la-1,j=lb-1;
        StringBuilder sb = new StringBuilder();
        while(i>=0 && j>=0){
            int sum =( a.charAt(i)-'0')
            +b.charAt(j)-'0'+add;
            
            add = sum/2;
            sum = sum%2;
            sb.insert(0,sum+"");
            i--;
            j--;
        }
        if(i>=0){
            j=i;
            b=a;
        }
        
        while(j>=0){
            int sum = b.charAt(j)-'0'+add;  //
            add = sum/2;
            sum = sum%2;
            sb.insert(0,sum+"");
            j--;
        }
        if(add>0){
            sb.insert(0,"1");  //
        }
        return sb.toString();
    }
}



别人的比较优美的写法

class Solution {
public:
    string addBinary(string a, string b) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int la = a.size();
        int lb = b.size();
        string sum = la > lb ? a : b;
        int overflow = 0;
        for( int i = 0; i < sum.size(); i ++ )
        {
            char ca = i < la ? a[la - i - 1] : '0';
            char cb = i < lb ? b[lb - i - 1] : '0';
            int bit = ca - '0' + cb - '0' + overflow;
            overflow = bit / 2;
            sum[sum.size() - i - 1] = bit % 2 + '0';
        }
        if(overflow)
        {
            sum = "1" + sum;
        }
        return sum;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值