码迷,mamicode.com
首页 > 其他好文 > 详细

67. Add Binary

时间:2016-05-13 02:06:41      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

**题目:
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"));
    }

}

67. Add Binary

标签:

原文地址:http://blog.csdn.net/it_yuntianhe/article/details/51346304

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!