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

LeetCode 67. Add Binary

时间:2016-09-17 00:10:27      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

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

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

这个题目只要注意各种情况你就成功了一大半,特别要注意的是对进位赋值后可能产生的变化,以及最后一位进位为1时,

我们要把这个1插进来。同时注意字符串的低位是我们数值的高位

class Solution {
public:
    string addBinary(string a, string b) {
        reverse(begin(a), end(a));
        reverse(begin(b), end(b));
        string result;
        char num = 0;
        int i = 0;
        for (;i < a.size() && i < b.size();++i)
        {
            if (a[i] == 0&&b[i] == 0&&num == 0)
            {
                result.insert(begin(result), 0);
            }
            if (a[i] == 1&&b[i] == 1&&num == 1)
            {
                result.insert(begin(result), 1);
            }
            if ((a[i] == 0&&b[i] == 1&&num == 1) || (a[i] == 1&&b[i] == 0&&num == 1) ||
                (a[i] == 1&&b[i] == 1&&num == 0))
            {
                result.insert(begin(result), 0);
                num = 1;
            }
            if (a[i] == 1&&b[i] == 0&&num == 0 || a[i] == 0&&b[i] == 1&&num == 0 ||
                a[i] == 0&&b[i] == 0&&num == 1)
            {
                result.insert(begin(result), 1);
                num = 0;
            }
        }
        if (i == a.size())
        {
            for (;i < b.size();++i)
            {
                if (b[i] == 0&&num == 0)
                    result.insert(begin(result), 0);
                if (b[i] == 0&&num == 1 || b[i] == 1&&num == 0)
                {
                    result.insert(begin(result), 1);
                    num = 0;
                }
                if (b[i] == 1&&num == 1)
                    result.insert(begin(result), 0);
            }
        }
        else
        {
            for (;i < a.size();++i)
            {
                if (a[i] == 0&&num == 0)
                    result.insert(begin(result), 0);
                if (a[i] == 1&&num == 1)
                    result.insert(begin(result), 0);
                if (a[i] == 0&&num == 1 || a[i] == 1&&num == 0)
                {
                    result.insert(begin(result), 1);
                    num = 0;
                }
                
            }
        }
        if (num == 1)result.insert(begin(result), 1);
        return result;
    }
};

 

LeetCode 67. Add Binary

标签:

原文地址:http://www.cnblogs.com/csudanli/p/5877499.html

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