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

第30题 Add Binary

时间:2015-01-06 18:06:01      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

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

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

Hide Tags
 Math String








Solution in Java:
public class Solution {
    public String addBinary(String a, String b) {
        int lengthA = a.length();
        int lengthB = b.length();
        int minLength, maxLength;
        String minStr, maxStr;
        if(lengthA<=lengthB){
            minLength = lengthA;
            minStr = a;
            maxLength = lengthB;
            maxStr = b;
        }else{
            minLength  = lengthB;
            minStr = b;
            maxLength = lengthA;
            maxStr = a;
        }
        String sum="";
        boolean carry = false;
        for(int i=0; i<minLength; i++){
            int digi1 = minStr.charAt(minLength-i-1)-'0';
            int digi2 = maxStr.charAt(maxLength-i-1)-'0';
            int sumDigi;
            if(carry)   sumDigi = digi1+digi2+1;
            else    sumDigi = digi1+digi2;
            if(sumDigi/2>0) carry = true;
            else    carry = false;
            sumDigi = sumDigi%2;
            String curDigi = String.valueOf(sumDigi);
            sum = curDigi +sum;
        }
        for(int i=maxLength-minLength-1; i>=0; i--){
            int digi = maxStr.charAt(i)-'0';
            if(carry) digi = digi+1;
            if(digi==2){
                digi=0;
                carry = true;
            }
            else    carry = false;
            String curDigi = String.valueOf(digi);
            sum = curDigi+sum;
        }
        if(carry)   sum = "1"+sum;
        return  sum;
    }
}

Note:
本来想直接用java中二进制,十进制和String间的转换,函数是:
二进制转十进制:int i=Integer.parseInt(str, 2) 第二个参数为进制树
十进制数转二进制String:String binStr = Integer.toBinaryString(i)
但在此题中不行,因为两个输入参数可能超过int和long的表示范围,会发生NumberFormatException,只能直接在String上操作。
获取String某一位的字符为str.charAt(i),得到char的int值,可以用这个char减去‘0’,可以得到该位的0或1的值。char可以直接做减法。
int转为String用函数String str= String.valueOf(i)
注意这个加法操作要从String的末尾到开头进行

第30题 Add Binary

标签:

原文地址:http://blog.csdn.net/amberfeb/article/details/42460251

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