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

leetcode学习笔记:Add Binary

时间:2015-08-15 23:09:51      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   string   binary   

一.题目描述

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

For example,
a = “11”
b = “1”
Return ”100”.

二.解题技巧

这道题考察两个二进制数相加,考虑到输入的是两组string,同时注意在运算时从左到右分别是从低位到高位,因此需要考虑对输入进行翻转处理,中间二进制树相加部分没有过多的设计障碍,主要是计算进位;在两组数据相加完成后,还需要考虑最高位的进位问题。

三.示例代码

#include <iostream>
#include <string>
using namespace std;

class Solution
{
public:
    string AddBinary(string a, string b)
    {
        size_t size = a.size() > b.size() ? a.size() : b.size();
        reverse(a.begin(), a.end());
        reverse(b.begin(), b.end());
        int CarryBit = 0;  // 进位
        string result; // 用于存放结果

        for (size_t i = 0; i < size; i++)
        {
            int a_num = a.size() > i ? a[i] - ‘0‘ : 0;
            int b_num = b.size() > i ? b[i] - ‘0‘ : 0;
            int val = (a_num + b_num + CarryBit) % 2;
            CarryBit = (a_num + b_num + CarryBit) / 2;  // 进位
            result.insert(result.begin(), val + ‘0‘);
        }

        if (CarryBit == 1)
            result.insert(result.begin(), ‘1‘);

        return result;
    }

};

测试代码:

#include "AddBinary.h"

using std::cout;
using std::cin;

int main()
{
    string a, b;
    cout << "Input the first string: ";
    cin >> a;
    cout << "\nInput the second string: ";
    cin >> b;

    Solution s;
    string result = s.AddBinary(a, b);

    cout << "\nThe Add Binary result is : " << result;

    return 0;
}

几个测试结果:

技术分享

技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode学习笔记:Add Binary

标签:leetcode   c++   string   binary   

原文地址:http://blog.csdn.net/liyuefeilong/article/details/47686201

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