【Leetcode长征系列】Add Binary

原题:

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

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

思路:先找到长的那个,然后根据进位判断是否继续运算还是进位。

代码:

class Solution {
public:
    string addBinary(string a, string b) {
        string bigger = a.size()>b.size()?a:b;
        string smaller = (bigger==a)?b:a;
        int carry = 0;
        int i = bigger.size()-1;
        int j = smaller.size()-1;
        
        for( ;j>=0; j--,i--){
            bigger[i]=bigger[i]-'0'+smaller[j]-'0'+carry;
            carry=bigger[i]/2;
            bigger[i]=(char)(bigger[i]%2+'0');
            
        }
        while(carry==1){
            if(i>=0){
                bigger[i]=bigger[i]-'0'+carry;
                carry=bigger[i]/2;
                bigger[i]=(char)(bigger[i]%2+'0');
                i--;
            }
            else{
                bigger = (char)(carry+'0') + bigger;
                break;
            }
        }
        return bigger;
    }
};



阅读更多
换一批

没有更多推荐了,返回首页