二進位制字串相加

壹頁書發表於2017-08-08
轉載自:
https://leetcode.com/problems/add-binary/discuss/

洋人寫的好優雅啊


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.         if(a == null || a.isEmpty()) {
  4.             return b;
  5.         }
  6.         if(b == null || b.isEmpty()) {
  7.             return a;
  8.         }
  9.         char[] aArray = a.toCharArray();
  10.         char[] bArray = b.toCharArray();
  11.         StringBuilder stb = new StringBuilder();

  12.         int i = aArray.length - 1;
  13.         int j = bArray.length - 1;
  14.         int aByte;
  15.         int bByte;
  16.         int carry = 0;
  17.         int result;

  18.         while(i > -1 || j > -1 || carry == 1) {
  19.             aByte = (i > -1) ? Character.getNumericValue(aArray[i--]) : 0;
  20.             bByte = (j > -1) ? Character.getNumericValue(bArray[j--]) : 0;
  21.             result = aByte ^ bByte ^ carry;
  22.             carry = ((aByte + bByte + carry) >= 2) ? 1 : 0;
  23.             stb.append(result);
  24.         }
  25.         return stb.reverse().toString();
  26.     }
  27. }


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-2143227/,如需轉載,請註明出處,否則將追究法律責任。

相關文章