leetcode #67 in cpp

Solution:

It is the same as #66. We use 2 instead of 10 as the modulo.

Code:

class Solution {
public:
    string addBinary(string a, string b) {
        int carry = 0;
        if(a.length() < b.length()){
            string temp = a;
            a = b;
            b = temp;
        }
        int alen = a.length();
        int blen = b.length();
        int i = 0;
        while(i<alen){
            if(i<blen){
                if(a[alen - i - 1] - '0' + b[blen - i - 1]-'0' + carry>=2){
                    a[alen - i - 1] = (a[alen - i - 1] - '0' + b[blen - i - 1]-'0' + carry) % 2 + '0';
                    carry = 1;  
                } 
                else{
                    a[alen - i - 1] = (a[alen - i - 1] - '0' + b[blen - i - 1]-'0' + carry) + '0';
                    carry = 0;
                }
            }else{
                if(a[alen - i - 1] - '0' + carry>=2){
                    a[alen - i - 1] = (a[alen - i - 1] - '0' + carry) % 2 + '0';
                    carry = 1;  
                }else{
                    a[alen - i - 1] = (a[alen - i - 1] - '0' + carry) + '0';
                    carry = 0;
                    break;
                }
            }
            i++;
        }
        if(carry) a = '1' + a;
        return a;
    }
};

阅读更多
文章标签: cpp leetcode
个人分类: interview
上一篇leetcode #66 in cpp
下一篇leetcode #68 in cpp
想对作者说点什么? 我来说一句

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

关闭
关闭