Leetcode 67. Add Binary

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Add Binary

2. Solution

  • Version 1
class Solution {
public:
    string addBinary(string a, string b) {
        reverse(a.begin(), a.end());
        reverse(b.begin(), b.end());
        int min = 0;
        int max = 0;
        int carry = 0;
        string s;
        string result;
        if(a.length() > b.length()) {
            max = a.length();
            min = b.length();
            s = a;
        }
        else {
            max = b.length();
            min = a.length();
            s = b;
        }
        for(int i = 0; i < min; i++) {
            int x = a[i] - 48;
            int y = b[i] - 48;
            int sum = x + y + carry;
            result += to_string(sum % 2);
            carry = sum>1?1:0;
        }
        for(int i = min; i < max; i++) {
            int x = s[i] - 48;
            int sum = x + carry;
            result += to_string(sum % 2);
            carry = sum>1?1:0;
        }
        if(carry) {
            result += to_string(carry);
        }
        reverse(result.begin(), result.end());
        return result;
    }
};
  • Version 2
class Solution {
public:
    string addBinary(string a, string b) {        
        int i = a.length() - 1;
        int j = b.length() - 1;
        int carry = 0;
        string result;
        while(i >= 0 || j >= 0) {
            int x = i>=0?(a[i]-48):0;
            int y = j>=0?(b[j]-48):0;
            int sum = x + y + carry;
            result += to_string(sum % 2);
            carry = sum>1?1:0;
            i--;
            j--;
        }
        if(carry) {
            result += to_string(carry);
        }
        reverse(result.begin(), result.end());
        return result;
    }
};

Reference

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

你可能感兴趣的:(Leetcode 67. Add Binary)