【leetcode】67. Add Binary

来源:互联网 发布:域名攻击 编辑:程序博客网 时间:2024/04/29 12:41

一、题目描述

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

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


题目解读:给两个二进制字符串,算出相加后的结果


思路:注意进位的情况。原理都懂,但是简洁的代码不好写。这里参考了别人的代码。


c++代码(10ms,6.61%)

class Solution {public:    string addBinary(string a, string b) {        string result="";         int i=a.size()-1;        int j=b.size()-1;        int c=0;        while(i>=0 || j>=0 || c==1){            c+= i>=0?a[i--]-'0':0;            c+= j>=0?b[j--]-'0':0;            result = char(c%2+'0') + result;            c/=2;        }//while        return result;    }};




0 0