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

67. Add Binary

时间:2018-11-18 14:17:29      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:public   add   begin   style   code   https   ever   bsp   pre   

https://leetcode.com/problems/add-binary/description/

class Solution {
public:
    string addBinary(string a, string b) {
        string res;
        int carry = 0;
        for (int ia = a.length() - 1, ib = b.length() - 1; ia >= 0 || ib >= 0; ia--, ib--)
        {
            int ca = ia < 0 ? 0 : a[ia] - 0;
            int cb = ib < 0 ? 0 : b[ib] - 0;
            int c = ca + cb + carry;
            res.push_back(c % 2 + 0);
            carry = c / 2;
        }
        if (carry > 0)
            res.push_back(carry + 0);
        reverse(res.begin(), res.end());
        return res;
    }
};

 

67. Add Binary

标签:public   add   begin   style   code   https   ever   bsp   pre   

原文地址:https://www.cnblogs.com/JTechRoad/p/9977699.html

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