首页 > 代码库 > LeetCode--Add Binary
LeetCode--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 m = a.length(); int n = b.length(); if(m == 0) return b; if(n == 0) return a; if(n>m) return addBinary(b,a); n--; m--; string res=""; int count = 0; while(n>=0 && m>=0) { int a_int = a[m]-48; int b_int = b[n]-48; int cal = count+a_int+b_int; count = cal/2; cal = cal%2; res += (char)(cal+48); m--; n--; } while(m>=0) { int a_int = a[m]-48; int cal = count+a_int; count = cal/2; cal = cal%2; res += (char)(cal+48); m--; } while(count>0) { res += (char)(count%2 + 48); count = count/2; } n = res.length()-1; int i=0; while(i<n) { char t = res[i]; res[i] = res[n]; res[n] = t; i++; n--; } return res; } };
LeetCode--Add Binary
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。