首页 > 其他 > 详细

LeetCode 67. Add Binary

时间:2017-08-30 20:42:17      阅读:241      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/pegasus923/p/7455134.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!