首页 > 代码库 > 【LeetCode】Add Binary
【LeetCode】Add Binary
Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
先进行对齐操作,然后从右往左逐位相加,注意进位即可。
代码写的比较长,但是很简单,就是分00,01,10,11四种情况并考虑进位。
class Solution {public: string addBinary(string a, string b) { if(a == "") return b; else if(b == "") return a; else {//align int size1 = a.size(); int size2 = b.size(); int size = max(size1, size2); if(size1 > size2) { int gap = size1-size2; string space(gap, ‘0‘); b = space+b; } else { int gap = size2-size1; string space(gap,‘0‘); a = space+a; } int tag = false; for(int i = size-1; i > 0; i --) { if(a[i] == ‘0‘ && b[i] == ‘0‘) { if(tag == true) {//carry bit used tag = false; a[i] = ‘1‘; } } else if(a[i] == ‘0‘ && b[i] == ‘1‘) { if(tag == true) //carry bit continues a[i] = ‘0‘; else a[i] = ‘1‘; } else if(a[i] == ‘1‘ && b[i] == ‘0‘) { if(tag == true) //carry bit continues a[i] = ‘0‘; else a[i] = ‘1‘; } else {//‘1‘ add ‘1‘ if(tag == true) //carry bit continues a[i] = ‘1‘; else {//carry bit generates a[i] = ‘0‘; tag = true; } } } //add the first digit if(a[0] == ‘0‘ && b[0] == ‘0‘) { if(tag == true) //carry bit used a[0] = ‘1‘; } else if(a[0] == ‘0‘ && b[0] == ‘1‘) { if(tag == true) {//carry bit continues a[0] = ‘0‘; a = "1"+a; } else a[0] = ‘1‘; } else if(a[0] == ‘1‘ && b[0] == ‘0‘) { if(tag == true) {//carry bit continues a[0] = ‘0‘; a = "1"+a; } else a[0] = ‘1‘; } else {//‘1‘ add ‘1‘ if(tag == true) //carry bit continues a[0] = ‘1‘; else //carry bit generates a[0] = ‘0‘; a = "1"+a; } return a; } }};
【LeetCode】Add Binary
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。