Leetcode 67. Add Binary

时间:2022-06-22
本文章向大家介绍Leetcode 67. Add Binary,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/82693764

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

1. Description

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/