码迷,mamicode.com
首页 > 其他好文 > 详细

67. Add Binary【LeetCode】

时间:2017-08-11 10:41:50      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:str   string   color   --   pre   logs   class   div   amp   

67. Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

 1 public class Solution {
 2     public String addBinary(String a, String b) {
 3         String res ="";
 4         int l1=a.length()-1;
 5         int l2=b.length()-1;
 6         
 7         int carry=0;
 8         for(int i=l1,j=l2;i>=0||j>=0;i--,j--){
 9             int sum=carry;
10             sum+=(i>=0)?(int)(a.charAt(i)-‘0‘):0;
11             sum+=(j>=0)?(int)(b.charAt(j)-‘0‘):0;
12             res =sum%2+res;
13             carry=sum/2;
14             
15         }
16         if(carry!=0){
17             res=carry+res;
18         }
19         return res;
20     }
21 }

 

67. Add Binary【LeetCode】

标签:str   string   color   --   pre   logs   class   div   amp   

原文地址:http://www.cnblogs.com/haoHaoStudyShare/p/7342707.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!