leetcode Add Binary

题目链接这里

public class Solution {
    public String addBinary(String a, String b) {
         StringBuilder result=new StringBuilder();

        if(a.length()<b.length())
        {
            String temp=a;
            a=b;
            b=temp;
        }

        int tempA;
        int tempB;
        int tempResult;
        int  auxiliary=0;
        for(int i=1;i<=b.length();i++)
        {
            tempA=a.charAt(a.length()-i)-'0';
            tempB=b.charAt(b.length()-i)-'0';
            tempResult=tempA+tempB+auxiliary;
            switch (tempResult) {
                case 3:
                auxiliary=1;
                tempResult=1;
                break;
            case 2:
                auxiliary=1;
                tempResult=0;
                break;
            case 1:
                auxiliary=0;
                break;
            case 0:
                auxiliary=0;
                break;
            default:
                break;
            }
            result.append((char)(tempResult+'0'));
        }

        out:for(int i=a.length()-b.length()-1;i>=0;i--)
        {
            tempA=a.charAt(i)-'0';

            tempResult=tempA+auxiliary;
            switch (tempResult) {
            case 2:
                auxiliary=1;
                tempResult=0;
                break;

            default:
            auxiliary=0;
                result.append((char)(tempResult+'0'));
                while(i>=1)
                {

                    result.append(a.charAt(i-1));
                    i--;
                }
                break out;
            }
            result.append((char)(tempResult+'0'));
        }


        if(auxiliary==1)
        {
            result.append('1');
        }

        return result.reverse().toString();
    }
}

你可能感兴趣的:(leetcode Add Binary)