67. Add Binary

**题目:
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
Subscribe to see which companies asked this question
**

思想:String ->Char->int->String

public class Add_Binary {

     /* main function to solve the problem*/
    public String addBinary(String a,String b)
    {
        int length_a = 0;
        int length_b = 0;
        length_a = getlength(a);
        length_b = getlength(b);
        return judge(a,b,length_a,length_b);
    }

    /* get the String's length*/
    public int getlength(String x)
    {
        int length = x.length();
        return length;
    }


    /* judge String a and String b and use function*/
    public String judge(String a,String b,int x,int y)
    {
        int max = Math.max(x,y);
        int min = Math.min(x,y);
        int carries = 0;
        String result = "";
        int j = 0 ;
        if(x==0||a==null)
            return b;
        else if(y==0||b==null)
            return a;
        else
        {
            //when a.length>0 and b.length>0
            while(max>0&&min>0)
            {
                int p = a.charAt(a.length()-j-1)-'0'+b.charAt(b.length()-j-1)-'0'+carries;
                result = p%2+ result;
                carries = p/2;
                j++;
                max--;
                min--;
            }
            //when a.length=min and it can't use the top function to solve problem;
            if(j==a.length())
            {
                while(j!=b.length())
                {
                    int p = b.charAt(b.length()-j-1)-'0'+carries;
                    result = p%2+ result;
                    carries = p/2;
                    j++;
                }
            }

            //when b.length=min and it can't use the top function to solve problem;
            else if(j==b.length())
            {
                while(j!=a.length())
                {
                    int p = a.charAt(a.length()-j-1)-'0'+carries;
                    result = p%2+ result;
                    carries = p/2;
                    j++;
                }
            }
            //At the Last,if carries == 1 ,we must put "1" in front of it;
            if(carries==1)
                result = "1"+result;
            return result;
        }
    }

    public static void main(String[] args) {
        Add_Binary newbinary = new Add_Binary();
        System.out.println(newbinary.addBinary("1101", "11"));
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值