Leetcode: Add Binary

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 }

 

你可能感兴趣的:(LeetCode)