首页 > 代码库 > HappyLeetcode37:Add Binary
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; }};
HappyLeetcode37:Add Binary
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。