letecode [67] - Add Binary
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"
题目大意:
给定两个包含”0“”1“字符串,计算他们的和,结果用二进制表示保存在字符串中。
理 解 :
从字符串末尾开始计算两数的和,保存在新的字符串c中。c初始化为较长的字符串。
设置surplus标记下一次和运算是否存在进位,若存在进位,则c[i] = 0 ,下下次和运算+1。
当和运算结束时,单独计算较长字符串的运算,处理较短字符串已计算完成,但surplus==1的情况。
代 码 C++:
class Solution { public: string addBinary(string a, string b) { int n1, n2, i, j,k, surplus = 0; string c; n1 = a.length(); n2 = b.length(); if (n1 > n2) { c = a; k = n1-1; } else { c = b; k = n2-1; } i = n1 - 1; j = n2 - 1; while (i >= 0 && j >= 0) { if (a[i] == b[j]) { if (a[i] == '1') { if (surplus == 1) { c[k] = '1'; } else { c[k] = '0'; } surplus = 1; } else { if (surplus == 1) { c[k] = '1'; } else { c[k] = '0'; } surplus = 0; } } else { if (surplus == 1) { c[k] = '0'; surplus = 1; } else { c[k] = '1'; surplus = 0; } } --i; --j; --k; } if (i < 0 && j < 0) { if (surplus == 1) c = "1" + c; } while (i >= 0) { if (i == 0 && a[i] == '1') { if (surplus == 1) { c[k] = '0'; c = "1" + c; } else { c[k] = '1'; } break; } if (a[i] == '1') { if (surplus == 1) { surplus = 1; c[k] = '0'; } else { surplus = 0; c[k] = '1'; break; } } else { if (surplus == 1) { c[k] = '1'; } else { c[k] = '0'; } break; } --i; --k; } while (j >= 0) { if (j == 0 && b[j] == '1') { if (surplus == 1) { c[k] = '0'; c = "1" + c; } else { c[k] = '1'; } break; } if (b[j] == '1') { if (surplus == 1) { surplus = 1; c[k] = '0'; } else { surplus = 0; c[k] = '1'; break; } } else { if (surplus == 1) { c[k] = '1'; } else { c[k] = '0'; } break; } --j; --k; } return c; } };
运行结果:
执行用时 : 8 ms 内存消耗 : 8.8 MB