LeetCode 67. Add Binary

Posted 浩然

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
View Code

以上是关于LeetCode 67. Add Binary的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode----67. Add Binary(java)

leetcode67. Add Binary

LeetCode 67. Add Binary

LeetCode 67. Add Binary

Leetcode 67. Add Binary

leetcode 67 Add Binary