Add Binary

Add Binary

问题:

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

思路:

  归并排序收尾工作

我的代码:

public class Solution {

    public String addBinary(String a, String b) {

        if(a == null)   return b;

        if(b == null)   return a;

        String s = "";

        int plus = 0;

        int i = a.length() - 1;

        int j = b.length() - 1;

        for(; i >= 0 && j >= 0; i--,j--)

        {

            int one = (int)(a.charAt(i) - '0');

            int two = (int)(b.charAt(j) - '0');

            int sum = one + two + plus;

            if(sum >= 2)

            {

                s = (sum - 2) + s;

                plus = 1;

            }

            else

            {

                s = sum + s;

                plus = 0;

            }

        }

        while(i >= 0)

        {

            int one = (int)(a.charAt(i) - '0');

            int sum = one + plus;

            if(sum >= 2)

            {

                s = (sum - 2) + s;

                plus = 1;

            }

            else

            {

                s = sum + s;

                plus = 0;

            }

            i--;

        }

        while(j >= 0)

        {

            int two = (int)(b.charAt(j) - '0');

            int sum = two + plus;

            if(sum >= 2)

            {

                s = (sum - 2) + s;

                plus = 1;

            }

            else

            {

                s = sum + s;

                plus = 0;

            }

            j--;

        }

        return plus == 0 ? s : 1 + s; 

    }

}
View Code

他人代码:

public class Solution {

    public String addBinary(String a, String b) {

        if(a.length() < b.length()){

            String tmp = a;

            a = b;

            b = tmp;

        }

        

        int pa = a.length()-1;

        int pb = b.length()-1;

        int carries = 0;

        String rst = "";

        

        while(pb >= 0){

            int sum = (int)(a.charAt(pa) - '0') + (int)(b.charAt(pb) - '0') + carries;

            rst = String.valueOf(sum % 2) + rst;

            carries = sum / 2;

            pa --;

            pb --;

        }

        

        while(pa >= 0){

            int sum = (int)(a.charAt(pa) - '0') + carries;

            rst = String.valueOf(sum % 2) + rst;

            carries = sum / 2;

            pa --;

        }       

        

        if (carries == 1)

            rst = "1" + rst;

        return rst;

    }

}
View Code

学习之处:

  • 他人代码里面用了两个循环就解决问题了,代码更加简洁,而我的代码里面用了三个循环,代码段太长了,需要精简
  • 进位的命名用carries更加专业一些
  • char c 类型的'0' 想转化成int 的0 int num = (int)(c - '0')
  • 这道题竟然花了好几遍才过

你可能感兴趣的:(binary)