二进制相加

public String addBinary(String a, String b) {


         String sa=a;        
        String sb=b;

        if (a.length() < b.length()) {
            for (int i = 0; i < b.length() - a.length(); i++) {
                sa = "0" + sa;
            }
        } else if (b.length() < a.length()) {

            for (int i = 0; i < a.length() - b.length(); i++) {
                sb = "0" + sb;
            }

        }


        String sum = "";

        int added = 0;
        for (int i = 0; i < sa.length(); i++) {
            int index1 = sa.length() - 1 - i;
            int index2 = sb.length() - 1 - i;

            int intA = Integer.parseInt(String.valueOf(sa.charAt(index1)));
            int intB = Integer.parseInt(String.valueOf(sb.charAt(index2)));

            int intC = intA + intB + added;

            if (intC >=2) {
                intC = intC-2;
                added = 1;
            } else {
                added = 0;
            }


            sum = intC + sum;


        }

        sum=added+sum;


        int index=sum.indexOf("1");

        if(index==-1)
        {
            sum="0";
            return "0";
        }
        else

        {
            return sum.substring(index,sum.length());
        }

    }
点赞