LeetCode笔记——67二进制求和

题目:给定两个二进制字符串,返回他们的和(用二进制表示)。

输入为非空字符串且只包含数字 1 和 0

示例 1:

输入: a = "11", b = "1"
输出: "100"

示例 2:

输入: a = "1010", b = "1011"
输出: "10101"

思路:首先将字符串转化为整数数组,从后往前一次相加,同时还存在最后一位扩展的情况。这次相加知道要用结果除以2得到进位,结果对2 求余数得到进位之后的数,但是还是有很多细节的为题没有考虑清楚,比如字符串与整数数组之间的转换,如何扩展高位,两个字符串长度不相等等。以下是参考网上大神的代码:

代码:

class Solution {
    public String addBinary(String a, String b) {
        int[]ca=new int[a.length()];
        int[]cb=new int[b.length()];
        for(int i=0;i         {
            ca[i]=a.charAt(i)-'0';
        }
        for(int j=0;j         {
            cb[j]=b.charAt(j)-'0';
        }
        if(a.length()         {
            int []temp=ca;
            ca=cb;
            cb=temp;   
        }
        int ai=ca.length-1;
        int bi=cb.length-1;
        int c=0;
        int result=0;
        while(ai>=0&&bi>=0)
        {
            result=ca[ai]+cb[bi]+c;
            c=result/2;
            ca[ai]=result%2;
            ai--;
            bi--;
        }
        while(ai>=0)
        {
            result=ca[ai]+c;
            c=result/2;
            ca[ai]=result%2;
            if(c==0)
                break;
             ai--;
        }
        for(int i=0;i         {
            ca[i]=ca[i]+'0';
        }
        if(c==0)
        {
            char[] ch = new char[ca.length];
            for (int i = 0; i < ca.length; i++) {
                ch[i] = (char) (ca[i]);
        }
             return new String(ch);
        }else
            {
                char[] ch = new char[ca.length + 1];
            ch[0] = '1';
            for (int i = 0; i < ca.length; i++) {
                ch[i + 1] = (char) (ca[i]);
            }
            return new String(ch);
        }
               
    }
}

你可能感兴趣的:(LeetCode笔记)