[C++]LeetCode: 9 Add Binary

来源:互联网 发布:java web程序开发入门 编辑:程序博客网 时间:2024/06/05 15:41

题目:

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

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

思路:直接从二进制的加法规则考虑入手

Attention:注意最后进位的考虑;字符串处理的细节。

AC Code:

class Solution {public:    string addBinary(string a, string b) {        //二进制字符串相加        //思路:直接做加法,考虑合理进位                //两种判空方法都可以        if(a == "0" || a.empty())            return b;        if(b == "0" || b.length() == 0)            return a;                string result;        //i,j是a,b字符串的索引,字符数减1        int i = a.length() - 1;        int j = b.length() - 1;        /* strlen所求是字符串的字节数; length所求是字符串中的字符数,不包括字符串结尾的NULL!!        int sizeb = strlen(b);        */        //aa,bb分别表示实际a[i],b[i]位的值(a,b长度不一定相同);rem和carry分别表示本位和进位        int aa, bb, rem, carry;        aa = bb = rem = carry = 0;                while((i >= 0) || (j >= 0))        {            //a[i] - '0'可以把a[i]转换为char类型; rem + ‘0’同理            //string 数组下标从零开始!!            aa = i < 0 ? 0 : a[i] - '0';            bb = j < 0 ? 0 : b[j] - '0';            rem = (aa + bb + carry)%2;            carry = (aa + bb + carry)/2;            result.push_back(rem + '0');            i--;            j--;        }                if(carry == 1)            result.push_back('1');                    //result是按照逆序存储的,需要翻转过来        reverse(result.begin(), result.end());        return result;    }};



0 0
原创粉丝点击