温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

二进制字符串相加

发布时间:2020-08-10 04:09:18 来源:ITPUB博客 阅读:121 作者:壹頁書 栏目:编程语言
转载自:
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. }


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI