LeetCode Oj 67. Add Binary

来源:互联网 发布:怪物猎人p3多玩数据库 编辑:程序博客网 时间:2024/06/03 10:55

67. Add Binary

 
 My Submissions
  • Total Accepted: 92800
  • Total Submissions: 327327
  • Difficulty: Easy

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss Pick One





class Solution {public:    string addBinary(string a, string b) {         reverse(a.begin(),a.end());         reverse(b.begin(),b.end());         string ans="";         int big=0;         int len=max(a.length(),b.length());         int x;         int y;         for(int i=0;i<len;i++)         {             if(i>=a.length()) x=0;             else x=a[i]-'0';             if(i>=b.length()) y=0;             else y=b[i]-'0';             ans=ans+(char)((x+y+big)%2+'0');             big=x+y+big>1 ? 1:0;         }         if(big) ans=ans+"1";         reverse(ans.begin(),ans.end());         return ans;    }};


0 0