首页 > 其他 > 详细

Add Binary

时间:2017-04-29 11:33:20      阅读:261      评论:0      收藏:0      [点我收藏+]

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) {
        int alen=a.length();
    	int blen=b.length();
    	int len=alen>blen?

(alen+1):(blen+1); StringBuffer sba=new StringBuffer(a).reverse(); StringBuffer sbb=new StringBuffer(b).reverse(); while(sba.length()<len) sba.append("0"); while(sbb.length()<len) sbb.append("0"); StringBuffer sb=new StringBuffer(""); int tmp = 0; for(int i=0;i<len;i++){ int ia=(int) (sba.charAt(i)-‘0‘); int ib=(int) (sbb.charAt(i)-‘0‘); int ic=ia+ib+tmp; tmp=0; if(ic==3){ sb.append("1"); tmp=1; } else if( ic==2){ sb.append("0"); tmp=1; } else{ new String(); sb.append(String.valueOf(ic)); tmp=0; } } // if last is 0 ; then delete if(sb.charAt(sb.length()-1)==‘0‘) sb.deleteCharAt(sb.length()-1); return sb.reverse().toString(); } }


Add Binary

原文:http://www.cnblogs.com/yangykaifa/p/6784711.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!