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

轉(zhuǎn)載自:
https://leetcode.com/problems/add-binary/discuss/

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


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

創(chuàng)新互聯(lián)公司是一家專注于成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作與策劃設(shè)計(jì),田林網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)十載,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:田林等地區(qū)。田林做網(wǎng)站價(jià)格咨詢: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. }


網(wǎng)頁題目:二進(jìn)制字符串相加
分享地址:http://muchs.cn/article48/jojdhp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、網(wǎng)站設(shè)計(jì)、營銷型網(wǎng)站建設(shè)App設(shè)計(jì)、動(dòng)態(tài)網(wǎng)站、定制網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都做網(wǎng)站