LeetCode | Add Binary

来源:互联网 发布:华为电视盒安装软件 编辑:程序博客网 时间:2024/05/17 02:21

题目:

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

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


思路:

本质上是反序遍历两个字符串,然后依次相加,相加过程与http://blog.csdn.net/lanxu_yy/article/details/11688591类似。

代码:

class Solution {public:    string addBinary(string a, string b) {        stack<bool> s;                int cur_a = a.size() - 1;        int cur_b = b.size() - 1;                int carry = 0;        while(cur_a > -1 || cur_b > -1){            int val_a = 0;            if(cur_a > -1)            {                val_a = char2int(a[cur_a--]);            }                        int val_b = 0;            if(cur_b > -1)            {                val_b = char2int(b[cur_b--]);            }            int tmp = val_a + val_b + carry;            carry = tmp / 2;            s.push((tmp % 2) == 1);        }                if(carry == 1){            s.push(true);        }                string result;        while(!s.empty()){            result.push_back(bool2char(s.top()));            s.pop();        }                return result;    }        int char2int(char c){        return c - '0';    }        char bool2char(bool b){        if(b){            return '1';        }        return '0';    }};


原创粉丝点击