关闭

leetcode #67 in cpp

标签: cppleetcode
30人阅读 评论(0) 收藏 举报
分类:

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;
    }
};

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:6852次
    • 积分:1393
    • 等级:
    • 排名:千里之外
    • 原创:139篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档