LeetCode:67 Add Binary(Week 1)

67. Add Binary

  • 题目

    • Given two binary strings, return their sum (also a binary string).
    • The input strings are both non-empty and contains only characters 1 or 0.

    Input: a = “11”, b = “1”
    Output: “100”

  • 解题思路

    • 二进制的高精度加法,对字符对应数字从低位逐位的相加,同时加上低位相加得到的进位,不断计算得到新的进位以及相加的结果,最后得到结果。
  • 代码

    // 二进制高精度加法
    
    class Solution {
    public:
        string addBinary(string a, string b) {
            string ans = ""; // 答案字符串
            int carry = 0; // 进位
            int i, j;
            for(i = a.length() - 1, j = b.length() - 1; i >= 0 && j >= 0; --i, --j) {
                ans += (a[i] - '0' + b[j] - '0' + carry) % 2 + '0';
                carry = a[i] - '0' + b[j] - '0' + carry >= 2 ? 1 : 0;
            }
    
            if(a.length() >= b.length()) {
                for(; i >= 0; --i) {
                    ans += (a[i] - '0' + carry) % 2 + '0';
                    carry = a[i] - '0' + carry >= 2 ? 1 : 0;
                }
            }
            else {
                for(; j >= 0; --j) {
                    ans += (b[j] - '0' + carry) % 2 + '0';
                    carry = b[j] - '0' + carry >= 2 ? 1 : 0;
                }
            }
    
            if(carry)
                ans += carry + '0';
    
            reverse(ans.begin(), ans.end()); 
            return ans;
        }
    };

猜你喜欢

转载自blog.csdn.net/lllllyt/article/details/82464372