码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode:Add Binary 二进制相加

时间:2014-04-29 13:12:20      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:leetcode   string   

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) {
       size_t len_a = a.length();
       size_t len_b = b.length();
       if(len_a == 0)
        return b;
       if(len_b == 0)
        return a;
       int i = len_a - 1;
       int j = len_b - 1;
       int increase = 0;
       stack<int> result_stk;
       while(i >= 0 && j >= 0)
       {
           int s = a[i] - ‘0‘ + b[j] - ‘0‘ + increase;
           increase = s / 2;
           int sum = s % 2;
           result_stk.push(sum);
           i--;
           j--;
       }
       while(i >= 0)
       {
           int s = a[i] - ‘0‘ + increase;
           increase = s / 2;
           int sum = s % 2;
           result_stk.push(sum);
           i--;
       }
       while(j >= 0)
       {
           int s = b[j] - ‘0‘ + increase;
           increase = s / 2;
           int sum = s % 2;
           result_stk.push(sum);
           j--;
       }
       if(increase == 1)
       result_stk.push(1);
       
       string result;
       while(!result_stk.empty())
       {
           result += result_stk.top() + ‘0‘;
           result_stk.pop();
       }
       return result;
    }
};


Leetcode:Add Binary 二进制相加

标签:leetcode   string   

原文地址:http://blog.csdn.net/u012118523/article/details/24648425

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!