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

LeetCode:Add Binary

时间:2015-06-12 16:40:21      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:

problems: 

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) {
        string result;
        int n=a.size()>b.size()?a.size():b.size();  //确定边界
        reverse(a.begin(),a.end()); //字符串加法不用倒着来
        reverse(b.begin(),b.end());
        
        int carry=0;  //用来表进位
        
        for(int i=0;i<n;i++)
        {
            int ai=i<a.size()?a[i]-‘0‘:0;
            int bi=i<b.size()?b[i]-‘0‘:0;
            int val=(ai+bi+carry)%2;
            carry=(ai+bi+carry)/2; 
            
            result.insert(result.begin(),val+‘0‘);
        } 
        if(carry==1)                        //相加最多多一位
            result.insert(result.begin(),‘1‘);
        return result;
    }
};

 

LeetCode:Add Binary

标签:

原文地址:http://www.cnblogs.com/xiaoying1245970347/p/4571843.html

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