码迷,mamicode.com
首页 > 其他好文 > 详细

19.2.12 [LeetCode 67] Add Binary

时间:2019-02-12 21:25:30      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:hid   16px   splay   input   etc   str   char   img   bsp   

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

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"
技术图片
 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         int i = a.size() - 1, j = b.size() - 1, last = 0;
 5         string ans = "";
 6         while (i >= 0 && j >= 0) {
 7             int now = a[i] + b[j] - 2 * 0 + last;
 8             ans = (char)(now % 2 + 0) + ans;
 9             last = now / 2;
10             i--, j--;
11         }
12         while (i >= 0) {
13             int now = a[i] - 0 + last;
14             ans = (char)(now % 2 + 0) + ans;
15             last = now / 2;
16             i--;
17         }
18         while (j >= 0) {
19             int now = b[j] - 0 + last;
20             ans = (char)(now % 2 + 0) + ans;
21             last = now / 2;
22             j--;
23         }
24         if (last > 0)
25             ans = (char)(last + 0) + ans;
26         return ans;
27     }
28 };
View Code

 

19.2.12 [LeetCode 67] Add Binary

标签:hid   16px   splay   input   etc   str   char   img   bsp   

原文地址:https://www.cnblogs.com/yalphait/p/10366892.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!