LeetCode 67. Add Binary
https://leetcode.com/problems/add-binary/description/
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
- 字符串简单题,模拟2进制加法。注意const用法。
- reverse - C++ Reference
- http://www.cplusplus.com/reference/algorithm/reverse/
1 // 2 // main.cpp 3 // LeetCode 4 // 5 // Created by Hao on 2017/3/16. 6 // Copyright © 2017年 Hao. All rights reserved. 7 // 8 9 #include <iostream> 10 #include <string> 11 using namespace std; 12 13 class Solution { 14 public: 15 string addBinary(string a, string b) { 16 string result = ""; 17 const size_t size = a.size() > b.size() ? a.size() : b.size(); 18 19 reverse(a.begin(), a.end()); 20 reverse(b.begin(), b.end()); 21 22 int carry = 0; 23 24 for (size_t i = 0; i < size; i ++) { 25 const int ai = i < a.size() ? a[i] - '0' : 0; 26 const int bi = i < b.size() ? b[i] - '0' : 0; 27 const int val = (ai + bi + carry) % 2; 28 carry = (ai + bi + carry) / 2; 29 result.insert(result.begin(), val + '0'); 30 } 31 32 if (carry == 1) 33 result.insert(result.begin(), '1'); 34 35 return result; 36 } 37 }; 38 39 int main () 40 { 41 Solution testSolution; 42 string sTest[] = {"11", "1", "100", "11"}; 43 44 for (int i = 0; i < 2; i ++) 45 cout << testSolution.addBinary(sTest[2 * i], sTest[2 * i + 1]) << endl; 46 47 return 0; 48 }