每日算法之四十六:Add Binary(二进制字符创相加)

二进制字符创相加,通过进位的方式逐位考虑。也可以把相加的过程抽象成一个函数。

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) {
        int a_len=a.length();
        int b_len=b.length();
        if(a_len==0)
            return b;
        if(b_len==0)
            return a;
        string result="";
        int max=(a_len>b_len?a_len:b_len);
        int j=a_len-1;
        int k=b_len-1;
        int sum=0;
        for(int i=0;i<max;i++,j--,k--)
        {
            if(j>=0)
            {
                sum+=a[j]-'0';
            }
            if(k>=0)
                sum+=b[k]-'0';
            result=(char)((sum&1)+'0')+result;
            sum=sum>>1;
        }
        if(sum>0)
            result='1'+result;
        return result;
        }
};

方法二:

// add a and b and carry, return a + b + carry.
// carry will be updated when add char.
char add_char(char a, char b, char &c)
{
    if (a == b && a == '1')
    {
        char ret = c;
        c = '1';
        return ret;
    }
    else if (a == b && a == '0')
    {
        char ret = c;
        c = '0';
        return ret;
    }
    else
    {
        if (c == '1')
        {
            return '0';
        }
        else
        {
            return '1';
        }
    }
}

// Given two binary strings, return their sum (also a binary string).
// For example,
// a = "11"
// b = "1"
// Return "100".
string add_binary(string a, string b)
{
    // Init result with the longest string.
    string result = a.size() > b.size() ? a : b;
    // Init carry with '0'.
    char carry = '0';

    const char *pa = a.data() + a.size() - 1;
    const char *pb = b.data() + b.size() - 1;
    string::iterator pc = result.begin() + result.size() - 1;

    while (pa != a.data() - 1 || pb != b.data() - 1)
    {
        if (pa == a.data() - 1)
        {
            *pc-- = add_char('0', *pb--, carry);
        }
        else if (pb == b.data() - 1)
        {
            *pc-- = add_char(*pa--, '0', carry);
        }
        else
        {
            *pc-- = add_char(*pa--, *pb--, carry);
        }
    }

    if (carry == '1')
    {
        return "1" + result;
    }

    return result;
}
时间: 2024-08-09 04:44:41

每日算法之四十六:Add Binary(二进制字符创相加)的相关文章

每日算法之四十二:Permutation Sequence (顺序排列第k个序列)

The set [1,2,3,-,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3): "123" "132" "213" "231" "312" "

每日算法之四十:Insert Interval

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9], insert and merge 

每日算法之四十四:Unique Path(矩阵中不重复路径的数目)

Unique Paths: A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked

每日算法之四十八:Plus One (数组表示的十进制加一进位)以及求Sqrt(x)

给定数组表示的十进制数,加一操作.结果依然用十进制的数组表示.这里主要注意最高位(digit[0])依然有进位,即溢出的情况. Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list. <span style=

经典算法题每日演练——第十六题 Kruskal算法

原文:经典算法题每日演练--第十六题 Kruskal算法 这篇我们看看第二种生成树的Kruskal算法,这个算法的魅力在于我们可以打一下算法和数据结构的组合拳,很有意思的. 一:思想 若存在M={0,1,2,3,4,5}这样6个节点,我们知道Prim算法构建生成树是从”顶点”这个角度来思考的,然后采用“贪心思想” 来一步步扩大化,最后形成整体最优解,而Kruskal算法有点意思,它是站在”边“这个角度在思考的,首先我有两个集合. 1. 顶点集合(vertexs): 比如M集合中的每个元素都可以认

46. 蛤蟆的数据结构笔记之四十六普里姆算法

46. 蛤蟆的数据结构笔记之四十六普里姆算法 本篇名言:"手莫伸 ,伸手必被捉.党与人民在监督 ,万目睽睽难逃脱.汝言惧捉手不伸 ,他道不伸能自觉 , 其实想伸不敢伸 ,人民咫尺手自缩.-- 陈毅" 连通图的生成树是一个极小的连通子图,它含有图中全部的顶点,但只有足以构成一棵树的n-1条边.所谓的最小成本,就是n个顶点,用n-1条边把一个连通图连接起来,并且使得权值的和最小.构造连通网的最小代价生成树,即最小生成树(Minimum Cost Spanning Tree). 找连通图的最

每日算法之三十九:Pow(x, n)

实现浮点类型的幂运算,函数原型为: double pow(double x, int n) 在求解这个问题的时候是一个很挣扎的过程,因为它不是报错而是一直提示你超出时间,那么必须一次次的考虑怎样降低时间复杂度. 首先最直接的思路是下面这样的,就跟直观的数学求解一样. double pow(double x, int n) { if(n==0) return 1.0; if(n<0) return 1.0/pow(x,-n); return x*pow(x,n-1); } 但是会提示你超出时间,这

每日算法之三十:Valid Sudoku (九宫格)

mnesia在频繁操作数据的过程可能会报错:** WARNING ** Mnesia is overloaded: {dump_log, write_threshold},可以看出,mnesia应该是过载了.这个警告在mnesia dump操作会发生这个问题,表类型为disc_only_copies .disc_copies都可能会发生. 如何重现这个问题,例子的场景是多个进程同时在不断地mnesia:dirty_write/2 mnesia过载分析 1.抛出警告是在mnesia 增加dump

每日算法之四十三:Rotate List (列表旋转k个元素)

Given a list, rotate the list to the right by k places, where k is non-negative. For example: Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL. 这里的k可能是比链表长度要大的数字,因此实际旋转的位置就是k%len(list).如果这个计算结果等于零或者等于len(list),