标签:
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; } }
标签:
原文地址:http://blog.csdn.net/amberfeb/article/details/42460251