67. Add Binary

来源:互联网 发布:淘宝买冰箱靠谱吗 编辑:程序博客网 时间:2024/05/01 22:47

题目:https://leetcode.com/problems/add-binary/

代码:

public class Solution {   public String addBinary(String a, String b) {        int lengtha = a.length();        int lengthb = b.length();        int i=lengtha-1,j=lengthb-1;        int add = 0;        StringBuffer temp = new StringBuffer();        StringBuffer res = new StringBuffer();        while(i>=0&&j>=0)        {            if(add==0)            {                if(a.charAt(i)=='1'&&b.charAt(j)=='1')                {                    add = 1;                    temp.append(0);                }                else if (a.charAt(i)=='0'&&b.charAt(j)=='0')                    temp.append(0);                else                    temp.append(1);            }            else            {                if(a.charAt(i)=='1'&&b.charAt(j)=='1')                {                    add = 1;                    temp.append(1);                }                else if(a.charAt(i)=='0'&&b.charAt(j)=='0')                {                    add = 0;                    temp.append(1);                }                else                 {                    add = 1;                    temp.append(0);                }            }            i--;j--;        }        if(lengtha>lengthb)        {            while(i>=0)            {                if(add==0)                     temp.append(a.charAt(i));                else                {                    if(a.charAt(i)=='1')                    {                        temp.append(0);                    }                    else                    {                        temp.append(1);                        add = 0;                    }                }                i--;            }        }        else        {            while(j>=0)            {                if(add==0)                     temp.append(b.charAt(j));                else                {                    if(b.charAt(j)=='1')                    {                        temp.append(0);                    }                    else                    {                        temp.append(1);                        add = 0;                    }                }                j--;            }        }        if(add==1)            temp.append(1);        for(i=temp.length()-1;i>=0;i--)            res.append(temp.charAt(i));        return res.toString();    }}5ms
0 0
原创粉丝点击