Add Binary

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

For example,
a = "11"
b = "1"
Return "100".

起初尝试把2个二进制数转换成十进制在相加,得到和之后在转换为二进制,最后发现二进制数位数太长转换成十进制数会溢出。直接采用先对齐,然后每位相加的方法即可。

public class Solution {
    
    public String addBinary(String a, String b) {
        String re = "";
        int size1 = a.length();
        int size2 = b.length();
        String longer = (a.length()>b.length())?a:b;
        String shorter = (b.length()<a.length())?b:a;
        int dis = Math.abs(size1-size2);
        //给短的补0以便和长的每位对齐
        for(int i=0;i<dis;i++){
            shorter = "0"+shorter;
        }
        int carry = 0;//进位逢二进一
        int size = longer.length();
        for(int j=size-1;j>=0;j--){
            int num1 = Integer.valueOf(longer.charAt(j)+"");
            int num2 = Integer.valueOf(shorter.charAt(j)+"");
            int sum = carry+num1+num2;//将每位以及低位的进位相加
            switch(sum){
                case 0:
                    carry = 0;
                    re = "0"+re;
                    break;
                case 1:
                    carry = 0;
                    re = "1"+re;
                    break;
                case 2:
                    carry = 1;
                    re = "0"+re;
                    break;
                case 3:
                    carry = 1;
                    re = "1"+re;
                    break;
                default:break;
            }
        }
        //若进位为1表明最高位相加产生进位补1
        if(carry==1){
            re = "1"+re;
        }
        return re;
    }
}

 

posted @ 2015-02-04 16:24  mrpod2g  阅读(222)  评论(0编辑  收藏  举报