package leetcode; public class demo_67 { public String addBinary(String a, String b) { String s=""; int i=a.length()-1; int j=b.length()-1; int c; //进位数 int add=0; while(i>=0&&j>=0) { //减去48是为了将ASCII的0和1 转换成正常的0和1 c= Integer.valueOf(a.charAt(i))-48+Integer.valueOf(b.charAt(j))-48+add; if(c>=2) { c=c%2; add=1; } else { add=0; } s=s+c; i=i-1; j=j-1; } if(j<0) { while(i>=0) { c=Integer.valueOf(a.charAt(i))-48+add; if(c>=2) { c=c%2; add=1; } else { add=0; } s=s+c; i=i-1; } } if(i<0) { while(j>=0) { c=Integer.valueOf(b.charAt(j))-48+add; if(c>=2) { c=c%2; add=1; } else { add=0; } s=s+c; j=j-1; } } if(add==1) { s=s+1; } StringBuffer sb=new StringBuffer(s); sb=sb.reverse(); s=sb.toString(); System.out.println(s); return s; } public static void main(String[] args) { // TODO Auto-generated method stub demo_67 d67=new demo_67(); String a="1010"; String b="1011"; d67.addBinary(a, b); } }