Leetcode 67. Add Binary

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

For example,
a = “11”
b = “1”
Return “100”.

按照二進制的加法規則進行編程就行了

class Solution {
public:
        string addBinary(string a, string b) {
                string ret = "";
                int carry = 0;
                for (int i = a.size() - 1, j = b.size() - 1; i >= 0 || j >= 0; i--, j--) {
                        int m = (i >= 0 && a[i] == '1');
                        int n = (j >= 0 && b[j] == '1');
                        ret = to_string((m + n + carry) & 0x1) + ret;
                        carry = (m + n + carry) >> 1;
                }
                return carry ? '1' + ret : ret;
        }
};
發佈了94 篇原創文章 · 獲贊 6 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章