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

LeetCode Add Binary

时间:2014-10-29 00:11:02      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   for   sp   div   on   

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        
 4        int la=a.length();
 5        int lb=b.length();
 6        char[] chars=new char[Math.max(la,lb)+1];
 7        int flag=0;
 8        int lastA=la-1;
 9        int lastB=lb-1;
10        int c=0;
11        int currA,currB;
12        for (int i = chars.length-1; i >=0; i--) {
13                    currA=lastA>=0?a.charAt(lastA):‘0‘;
14                    currB=lastB>=0?b.charAt(lastB):‘0‘;
15                    c=currA-‘0‘+currB-‘0‘+flag;
16                    if (c==3) {
17                     chars[i]=‘1‘;
18                     flag=1;
19                 }else if (c==2) {
20                     chars[i]=‘0‘;
21                     flag=1;
22                 }else {
23                     chars[i]=(char) (‘0‘+c);
24                     flag=0;
25                 }
26                    lastA--;
27                    lastB--;
28        }
29        String string=new String(chars);
30        if (string.charAt(0)==‘0‘) {
31         return string.substring(1);
32     }
33        return string;
34     }
35 }

 

LeetCode Add Binary

标签:style   blog   io   color   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/birdhack/p/4058245.html

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