标签:leetcode
Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
两字符串表示的2进制数。求它们的和。
直接模拟,从最后一位开始每一位都相加,结果保存在栈中。
class Solution { public: string addBinary(string a, string b) { stack<int>s; int n = a.size() - 1,m = b.size() - 1; int add = 0; //进位 while (n >= 0 && m >= 0) { // 计算每一位的结果,存在栈中 if (a[n] == '0' && b[m] == '0') { if (add == 1) s.push('1'); else s.push('0'); add = 0; } else if (a[n] == '0' && b[m] == '1' ||a[n] == '1' && b[m] == '0') { if (add == 1) {s.push('0');add = 1;} else {s.push('1');add = 0;} } else { if (add == 1) s.push('1'); else s.push('0'); add = 1; } n--; m--; } // 两字符串有一字符串为空 则另作讨论 if (n < 0 && m < 0) { if (add == 1) s.push('1'); } else if (n >= 0 && m < 0) { while (n >= 0) { if (a[n] == '1') { if (add == 1) {s.push('0');add = 1;} else {s.push('1');add = 0;} } else if (a[n] == '0') { if (add == 1 ) s.push('1'); else s.push('0'); add = 0; } n--; } if (add == 1) s.push('1'); } else if (n < 0 && m >= 0) { while (m >= 0) { if (b[m] == '1') { if (add == 1) {s.push('0');add = 1;} else {s.push('1');add = 0;} } else if (b[m] == '0') { if (add == 1 ) s.push('1'); else s.push('0'); add = 0; } m--; } if (add == 1) s.push('1'); } string c; while(!s.empty()) { // 每一位的结果,从栈中取出,存入string中 c += s.top(); s.pop(); } return c; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:leetcode
原文地址:http://blog.csdn.net/u014705854/article/details/47260227