二进制字符串相加

转载自:
https://leetcode.com/problems/add-binary/discuss/

洋人写的好优雅啊


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

创新互联公司是一家专注于成都网站设计、成都网站制作与策划设计,田林网站建设哪家好?创新互联公司做网站,专注于网站建设十载,网设计领域的专业建站公司;建站业务涵盖:田林等地区。田林做网站价格咨询:18980820575

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. }



本文名称:二进制字符串相加
网站网址:http://scyanting.com/article/jojdhp.html