LeetCode题解——Add Binary

来源:互联网 发布:淘宝刷流量有用么 编辑:程序博客网 时间:2024/04/30 02:33

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

For example,
a = "11"
b = "1"

Return "100".

思路:最直接的想法,从最后一位开始,逐位运算。

class Solution {public://特殊输入:空字符串,10+1;11+11,1111+11,1011+11;    string addBinary(string a, string b) {        if(!a.size()) return b;        if(!b.size()) return a;        string longstr = a.size()>=b.size()?a:b;        string shortstr = a.size()>=b.size()?b:a;        int overtake = 0;        int i=longstr.size()-1;        for(int j =shortstr.size()-1; j>=0;i--,j--){            int tempvalue = int(longstr[i]-'0'+shortstr[j]-'0')+ overtake ;            if(tempvalue<=1){                longstr[i] = tempvalue+'0';                overtake = 0;            }            else{                longstr[i] = tempvalue-2+'0';                overtake = 1;            }        }        while(i>=0){            int tempvalue = longstr[i]-'0'+overtake;             if(tempvalue<=1){                longstr[i] = tempvalue+'0';                return longstr;            }            else{                longstr[i] = tempvalue-2+'0';                overtake = 1;            }            i--;        }        if(overtake == 1){            longstr = '1'+longstr;        }         return longstr;    }};


0 0
原创粉丝点击