标签:
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 n1=new StringBuilder(a).reverse().toString(); String n2=new StringBuilder(b).reverse().toString(); StringBuilder sb= new StringBuilder(); int l=Math.min(a.length(),b.length()); int carry=0; int digit=0; for(int i=0;i<l;i++){ digit=carry+n1.charAt(i)-‘0‘+n2.charAt(i)-‘0‘; if(digit==2){ digit=0; carry=1; } else if(digit==3){ digit=1; carry=1; }else{ carry=0; } sb.insert(0,digit); } if(a.length()>b.length()){ for(int i=l;i<a.length();i++){ digit=carry+n1.charAt(i)-‘0‘; if(digit==2){ digit=0; carry=1; }else{ carry=0; } sb.insert(0,digit); } } if(a.length()<b.length()){ for(int i=l;i<b.length();i++){ digit=carry+n2.charAt(i)-‘0‘; if(digit==2){ digit=0; carry=1; }else{ carry=0; } sb.insert(0,digit); } } if(carry==1){ sb.insert(0,carry); } return sb.toString(); } }
标签:
原文地址:http://www.cnblogs.com/joannacode/p/4421181.html