溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

二進(jìn)制字符串相加

發(fā)布時間:2020-08-10 04:09:18 來源:ITPUB博客 閱讀:132 作者:壹頁書 欄目:編程語言
轉(zhuǎn)載自:
https://leetcode.com/problems/add-binary/discuss/

洋人寫的好優(yōu)雅啊


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


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI