HappyLeetcode37:Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
这道题挺简单的,不多说了,代码奉上
class Solution { public: string addBinary(string a, string b) { int lengtha = a.length(); int lengthb = b.length(); int indexa = a.length() - 1; int indexb = b.length() - 1; int res = 0;//设置进位 string result; map<char, int> mapping; mapping[‘1‘] = 1; mapping[‘0‘] = 0; int value; while (indexa>=0||indexb>=0) { if (indexa < 0) value = 0 + mapping[b[indexb]] + res; else if (indexb < 0) value = mapping[a[indexa]] + 0 + res; else value = mapping[a[indexa]] + mapping[b[indexb]] + res; if (value >= 2) { res = 1; value %=2; } else { res = 0; } result.push_back(value+‘0‘-0); indexa--; indexb--; } if (res == 1) result.push_back(res + ‘0‘ - 0); reverse(result.begin(), result.end()); return result; } };
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。