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

67. Add Binary

时间:2016-03-10 12:38:48      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

/*
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) {
        if (a == "" && b == "") return "";
        
        string result = "";
        int c = 0, i = a.length()-1, j = b.length()-1;
        while (i >= 0 || j >= 0) {
            
            c += i < a.length() ? (a[i] - 0) : 0;
            c += j < b.length() ? (b[j] - 0) : 0;
            
            result = char(c%2 + 0) + result;
            c /= 2;
            --i, --j;
        }
        
        return c ? char(c+0) + result : result;
    }
};

 

67. Add Binary

标签:

原文地址:http://www.cnblogs.com/linjj/p/5261257.html

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