Add Binary_LeetCode
Decription:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
解题思路:
分别从a和b字符串的最后一位开始遍历,用char - '0'将char类型转换成int类型。
定义count和jinwei两个变量,count为a和b目前所遍历到的字符转int后的和,jinwei为下一位是否需要进位。
但是a和b的长度可能不同,存在一方先遍历结束的情况,因此需要在同时遍历完a和b后,对比较长的字符串进行单独遍历。
由于是从后开始遍历,因此用于存储结果的string在最后应该进行转置reverse。
代码比较长,但是比较好理解。
代码:
class Solution { public: string addBinary(string a, string b) { int x = a.length()-1; int y = b.length()-1; string c = ""; int count = 0; int jinwei = 0; while (x >= 0 && y >= 0) { count = (a[x] - '0') + (b[y] - '0') + jinwei; if (count == 0) { jinwei = 0; c += '0'; x--; y--; } else if (count == 1) { jinwei = 0; c += '1'; x--; y--; } else if (count == 2) { jinwei = 1; c += '0'; x--; y--; } else { jinwei = 1; c += '1'; x--; y--; } } while (x>=0) { count = (a[x] - '0') + jinwei; if (count == 0) { jinwei = 0; c += '0'; x--; } else if (count == 1) { jinwei = 0; c += '1'; x--; } else if (count == 2) { jinwei = 1; c += '0'; x--; } else { jinwei = 1; c += '1'; x--; } } while (y>=0) { count = (b[y] - '0') + jinwei; if (count == 0) { jinwei = 0; c += '0'; y--; } else if (count == 1) { jinwei = 0; c += '1'; y--; } else if (count == 2) { jinwei = 1; c += '0'; y--; } else { jinwei = 1; c += '1'; y--; } } if (jinwei == 1) { c += '1'; } reverse(c.begin(),c.end()); return c; } };
-

浙公网安备 33010602011771号