今天晚上总结了一下c++中string的常用的属性和方法,一时手痒,所以就找了个题目练练手,记录一下。
题目描述
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和1001进行相加,很明显,结果是1010。计算结果可以将1补充为0001,这样就可以数据对齐,然后就可以方便计算而不容易出现空指针了。
题目代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { public: string addBinary(string a, string b) { int alen = a.size(); int blen = b.size(); int mlen = max(alen, blen); string res = ""; int carry = 0; for(int i = 0; i < mlen; i++){ int tempa = alen>i?a[alen-i-1]-'0':0; int tempb = blen>i?b[blen-i-1]-'0':0; int tres = tempa+tempb+carry; if(tres == 0){ res.insert(0,1,'0'); carry = 0; }else if(tres == 1){ res.insert(0,1,'1'); carry = 0; }else if(tres == 2){ res.insert(0,1,'0'); carry = 1; }else if(tres == 3){ res.insert(0,1,'1'); carry = 1; } } if(carry == 1){ res.insert(0,1,'1'); } return res; } };
|