67. Add Binary
慶城網站制作公司哪家好,找創(chuàng)新互聯(lián)建站!從網頁設計、網站建設、微信開發(fā)、APP開發(fā)、響應式網站建設等網站項目制作,到程序開發(fā),運營維護。創(chuàng)新互聯(lián)建站從2013年創(chuàng)立到現(xiàn)在10年的時間,我們擁有了豐富的建站經驗和運維經驗,來保證我們的工作的順利進行。專注于網站建設就選創(chuàng)新互聯(lián)建站。
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
思路:
1.將兩個字符串按數(shù)組相加得到新數(shù)組。
2.將新數(shù)組轉換成結果。
代碼如下:
class Solution { public: string addBinary(string a, string b) { int sizeA = a.size(); int sizeB = b.size(); int carry = 0; vectorresult; string resultStr; if (sizeA < sizeB) return addBinary(b, a); for (int i = 0; i < sizeB; i++) { int cur = (a[sizeA - i - 1] - '0') + (b[sizeB - i - 1] - '0') + carry; if (cur < 2) { result.push_back(cur); carry = 0; } else if (cur == 2) { result.push_back(0); carry = 1; } else if (cur == 3) { result.push_back(1); carry = 1; } } for (int j = sizeB; j < sizeA; j++) { int cur = (a[sizeA - j - 1] - '0') + carry; if (cur < 2) { result.push_back((a[sizeA - j - 1] - '0') + carry); carry = 0; } else if (cur == 2) { result.push_back(0); carry = 1; } else if (cur == 3) { result.push_back(1); carry = 1; } } if (carry == 2) { result.push_back(0); result.push_back(1); } else if ( carry == 1) { result.push_back(1); } for (int k = 0; k < result.size(); k++) { if (result[result.size() - 1 - k] == 1) { resultStr.append(1, '1'); } else { resultStr.append(1, '0'); } } return resultStr; } };
2016-08-10 23:39:26