#Leetcode# 67. Add Binary

https://leetcode.com/problems/add-binary/

 

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

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

代码1:

class Solution {
public:
    string addBinary(string a, string b) {
        string res;
        int na = a.size();
        int nb = b.size();
        int n = max(na, nb);
        bool carry = false;
        if (na > nb) {
            for (int i = 0; i < na - nb; ++i) b.insert(b.begin(), '0');
        }
        else if (na < nb) {
            for (int i = 0; i < nb - na; ++i) a.insert(a.begin(), '0');
        }
        for (int i = n - 1; i >= 0; --i) {
            int tmp = 0;
            if (carry) tmp = (a[i] - '0') + (b[i] - '0') + 1;
            else tmp = (a[i] - '0') + (b[i] - '0');
            if (tmp == 0) {
                res.insert(res.begin(), '0');
                carry = false;
            }
            else if (tmp == 1) {
                res.insert(res.begin(), '1');
                carry = false;
            }
            else if (tmp == 2) {
                res.insert(res.begin(), '0');
                carry = true;
            }
            else if (tmp == 3) {
                res.insert(res.begin(), '1');
                carry = true;
            }
        }
        if (carry) res.insert(res.begin(), '1');
        return res;
    }
};

  LeetCode 的格式很难受了

代码2:

#include <bits/stdc++.h>
using namespace std;

char a[50], b[50];
char ans[1010];

int main() {
    scanf("%s%s", a, b);
    int lena = strlen(a), lenb = strlen(b);
    for(int i = 0; i < lena / 2; i ++)
        swap(a[i], a[lena - i - 1]);
    for(int i = 0; i < lenb / 2; i ++)
        swap(b[i], b[lenb - i - 1]);

    int len = min(lena, lenb), maxlen = max(lena, lenb);
    int cnt = 0;
    int k = 0;
    for(int i = 0; i < len; i ++) {
        ans[cnt ++] = (a[i] - '0' + b[i] - '0' + k) % 2 + '0';
        k = (a[i] - '0' + b[i] - '0' + k) / 2;
    }
    for(int i = len; i < maxlen; i ++) {
        if(maxlen == lena) {
            ans[cnt ++] = (a[i] - '0' + k) % 2 + '0';
            k = (a[i] - '0' + k) / 2;
        } else {
            ans[cnt ++] = (b[i] - '0' + k) % 2 + '0';
            k = (b[i] - '0' + k) / 2;
        }
    }

    if(k) ans[cnt ++] = '1';

    for(int i = 0; i < cnt / 2; i ++)
        swap(ans[i], ans[cnt - i - 1]);

    printf("%s\n", ans);
    return 0;
}

  

posted @ 2018-11-20 22:06  丧心病狂工科女  阅读(96)  评论(0编辑  收藏  举报