Leetcode: Add Binary

二进制字符串相加
本文介绍了一种使用StringBuffer实现的二进制字符串相加的方法。通过从字符串末尾开始遍历并逐位相加的方式,实现了二进制字符串的加法运算。
Given two binary strings, return their sum (also a binary string).

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

 我自己的做法:用StringBuffer, a和b都从末尾扫描到开头,而StringBuffer则是每次存在开头。循环则是只要aindex>=0 or bindext>=0 or carry>0就继续。加法则是分成3部分,依次判断aindex, bindex, carry是否满足加的条件,满足就加。这样写结构非常清晰。可以作为这类题的解题模板

 1 public class Solution {
 2     public String addBinary(String a, String b) {
 3         if (a==null || a.length()==0) return b;
 4         if (b==null || b.length()==0) return a;
 5         StringBuffer res = new StringBuffer();
 6         int aindex = a.length() - 1;
 7         int bindex = b.length() - 1;
 8         int digit = 0;
 9         int carry = 0;
10         while (aindex>=0 || bindex>=0 || carry>0) {
11             int result = 0;
12             if (aindex >= 0) {
13                 result += (int)(a.charAt(aindex) - '0');
14                 aindex--;
15             }
16             if (bindex >= 0) {
17                 result += (int)(b.charAt(bindex) - '0');
18                 bindex--;
19             }
20             if (carry > 0) {
21                 result += carry;
22             }
23             digit = result % 2;
24             carry = result / 2;
25             res.insert(0, digit);
26         }
27         return res.toString();
28     }
29 }

 别人的代码,用StringBuffer,差不多

 1 public String addBinary(String a, String b) {
 2     if(a==null || a.length()==0)
 3         return b;
 4     if(b==null || b.length()==0)
 5         return a;
 6     int i=a.length()-1;
 7     int j=b.length()-1;
 8     int carry = 0;
 9     StringBuilder res = new StringBuilder();
10     while(i>=0&&j>=0)
11     {
12         int digit = (int)(a.charAt(i)-'0'+b.charAt(j)-'0')+carry;
13         carry = digit/2;
14         digit %= 2;
15         res.append(digit);
16         i--;
17         j--;
18     }
19     while(i>=0)
20     {
21         int digit = (int)(a.charAt(i)-'0')+carry;
22         carry = digit/2;
23         digit %= 2;
24         res.append(digit);
25         i--;
26     }
27     while(j>=0)
28     {
29         int digit = (int)(b.charAt(j)-'0')+carry;
30         carry = digit/2;
31         digit %= 2;
32         res.append(digit);
33         j--;
34     }      
35     if(carry>0)
36     {
37         res.append(carry);
38     }
39     return res.reverse().toString();
40 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值