标签:style blog io color ar sp div on log
题目:给定两个二进制字符串,返回相加的结果,也是二进制表示。
主要就是考查进位如何操作,以及最后如果加完之后进位还是1的话那么不能漏了还要加1.跟之前有做过一题的类似。
因为这题easy就是判断,所以直接贴代码了,感觉好长的样子。
class Solution { public: string addBinary(string a, string b) { if(a.size()==0 || b.size()==0) return a+b; string ans = ""; int up = 0, lena = a.size() - 1, lenb = b.size() - 1; while(lena >= 0 && lenb >= 0) { if (a[lena] == b[lenb] && a[lena] == ‘1‘) { if(up == 1) ans = ‘1‘ + ans; else { ans = ‘0‘ + ans; up=1; } } else if (a[lena] == ‘0‘ && b[lenb] == ‘0‘) { if(up == 1) {ans = ‘1‘ + ans; up = 0;} else ans = ‘0‘ + ans; } else { if(up == 1) {ans = ‘0‘ + ans; up = 1;} else ans = ‘1‘+ ans; } lena--; lenb--; } while(lena>=0) { if(a[lena] == ‘1‘ && up == 1) ans = ‘0‘ + ans; else if (up == 1) { ans = ‘1‘ + ans; up = 0; } else { ans = a[lena] + ans; } lena--; } while(lenb>=0) { if(b[lenb] == ‘1‘ && up == 1) ans = ‘0‘ + ans; else if (up == 1) { ans = ‘1‘ + ans; up = 0; } else { ans = b[lenb] + ans; } lenb--; } if(up == 1) ans = ‘1‘ + ans; return ans; } };
标签:style blog io color ar sp div on log
原文地址:http://www.cnblogs.com/higerzhang/p/4084283.html