[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) { if(a.length()==0) return b; if(b.length()==0) return a; int len=a.length()<b.length()?a.length():b.length(); if(len==a.length()) swap(a,b); int len1=a.length(); int len2=b.length(); int i; for(i=0;i<len;i++) { a[len1-1-i]=(a[len1-1-i]-'0')+(b[len2-1-i]-'0')+'0'; } for(i=len1-1;i>0;i--) { if(a[i]>='2') { a[i]=(a[i]-'0')%2+'0'; a[i-1]=(a[i-1]-'0'+1)+'0'; } } if(a[0]>='2') { string ans(a,1,len1-1); if(a[0]=='2') return "10"+ans; else return "11"+ans; } else return a; } };