Given two binary strings, return their sum (also a binary string).For example, a = "11" b = "1" Return "100".
这道题不难,注意分清情况。
public class Solution {public String addBinary(String a, String b) {String str="";int i=a.length()-1;int j=b.length()-1;int pass=0;while(i >= 0 && j>=0){if(Character.getNumericValue(a.charAt(i))+Character.getNumericValue(b.charAt(j))+pass >= 2){int digit=(Character.getNumericValue(a.charAt(i))+Character.getNumericValue(b.charAt(j))+pass)-2;str=Integer.toString(digit)+str;pass=1;i--;j--;}else{int digit=Character.getNumericValue(a.charAt(i))+Character.getNumericValue(b.charAt(j))+pass;str=Integer.toString(digit)+str;pass=0;i--;j--;}}while(j>=0){if(Character.getNumericValue(b.charAt(j))+pass>=2){int digit=Character.getNumericValue(b.charAt(j))+pass-2;str=Integer.toString(digit)+str;pass=1;j--;}else{int digit=Character.getNumericValue(b.charAt(j))+pass;str=Integer.toString(digit)+str;pass=0;j--;}}while(i>=0){if(Character.getNumericValue(a.charAt(i))+pass>=2){int digit=Character.getNumericValue(a.charAt(i))+pass-2;str=Integer.toString(digit)+str;pass=1;i--;}else{int digit=Character.getNumericValue(a.charAt(i))+pass;str=Integer.toString(digit)+str;pass=0;i--;}}if(pass==1){str=Integer.toString(pass)+str;}return str;} }