首页 > 代码库 > Add Binary
Add Binary
题目描述:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
解题方案:
1 class Solution { 2 public: 3 string addBinary(string a, string b) { 4 int LocationA = a.size() - 1; 5 int LocationB = b.size() - 1; 6 7 if (LocationA == -1) { 8 return b; 9 }10 if (LocationB == -1) {11 return a;12 }13 string result;14 int carry = 0;15 16 while((LocationA >= 0) && (LocationB >= 0)) {17 int temp = ((a[LocationA] - ‘0‘) + (b[LocationB] - ‘0‘) + carry) % 2;18 carry = ((a[LocationA] - ‘0‘) + (b[LocationB] - ‘0‘) + carry) / 2;19 result.append(1, temp + ‘0‘);20 --LocationA;21 --LocationB;22 }23 if (LocationA != -1) {24 while(LocationA >= 0) {25 int temp = ((a[LocationA] - ‘0‘) + carry) % 2;26 carry = ((a[LocationA] - ‘0‘) + carry) / 2;27 result.append(1, temp + ‘0‘);28 --LocationA;29 }30 }31 if (LocationB != -1) {32 while(LocationB >= 0) {33 int temp = ((b[LocationB] - ‘0‘) + carry) % 2;34 carry = ((b[LocationB] - ‘0‘) + carry) / 2;35 result.append(1, temp + ‘0‘);36 --LocationB;37 }38 }39 40 if (carry != 0) {41 result.append(1, carry + ‘0‘);42 }43 44 int i = 0;45 int j = result.size() - 1;46 //将字符串反转47 while (i <= j) {48 char temp = result[i];49 result[i] = result[j];50 result[j] = temp;51 ++i;52 --j;53 }54 return result;55 }56 };
Add Binary
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。