首页 > 其他 > 详细

LeetCode_Add Binary

时间:2015-05-14 18:40:05      阅读:114      评论:0      收藏:0      [点我收藏+]

一.题目

Add Binary

  Total Accepted: 41532 Total Submissions: 166966My Submissions

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

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

Show Tags
Have you met this question in a real interview?  
Yes
 
No

Discuss









二.解题技巧

    这道题没有什么技巧,只是考虑到两个二进制数相加,得到的结果最多也就比最长的那个二进制数多一位,因此可以预先分配一个string,然后从最低位开始计算,在输出最终结果的时候,需要考虑最高位是否为0的情况。在逐位进行相加的时候,还需要考虑进位的情况。
    

三.实现代码

class Solution
{
public:
    string addBinary(string a, string b)
    {
        int A_SIZE = a.size();
        int B_SIZE = b.size();

        int C_SIZE = (A_SIZE > B_SIZE? A_SIZE : B_SIZE) + 1;

        string Result(C_SIZE, '0');
        unsigned char TmpA = '0';
        unsigned char TmpB = '0';
        unsigned char C = '0';
        unsigned char TmpBit = '0';

        A_SIZE--;
        B_SIZE--;
        while (A_SIZE >= 0 || B_SIZE >= 0)
        {
            TmpA = '0';
            TmpB = '0';

            if (A_SIZE >= 0)
            {
                TmpA = a[A_SIZE--];
            }

            if (B_SIZE >= 0)
            {
                TmpB = b[B_SIZE--];
            }

            unsigned char Count = (TmpA - '0') + (TmpB - '0') + (C - '0');

            TmpBit = Count % 2 + '0';
            C = Count / 2 + '0';

            Result[--C_SIZE] = TmpBit;
        }

        Result[--C_SIZE] = C;

        if (Result[0] == '0')
        {
            return Result.substr(1);
        }

        return Result;
    }
};




四.体会

    这道题是一个细节题,没有过多的算法在里面。



版权所有,欢迎转载,转载请注明出处,谢谢技术分享
技术分享




LeetCode_Add Binary

原文:http://blog.csdn.net/sheng_ai/article/details/45723861

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!