二进制字符串相加
转载自:
https://leetcode.com/problems/add-binary/discuss/
洋人写的好优雅啊
分享文章:二进制字符串相加
文章链接:http://ybzwz.com/article/jojdhp.html
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".
-
public class Solution{
-
public String addBinary(String a, String b) {
-
if(a== null || a.isEmpty()) {
-
return b;
-
}
-
if(b== null || b.isEmpty()) {
-
return a;
-
}
-
char[] aArray= a.toCharArray();
-
char[] bArray= b.toCharArray();
-
StringBuilder stb= new StringBuilder();
-
-
int i= aArray.length - 1;
-
int j= bArray.length - 1;
-
int aByte;
-
int bByte;
-
int carry= 0;
-
int result;
-
-
while(i> -1|| j> -1|| carry== 1) {
-
aByte= (i> -1) ? Character.getNumericValue(aArray[i--]) : 0;
-
bByte= (j> -1) ? Character.getNumericValue(bArray[j--]) : 0;
-
result = aByte ^ bByte ^ carry;
-
carry= ((aByte+ bByte+ carry) >= 2) ? 1: 0;
-
stb.append(result);
-
}
-
return stb.reverse().toString();
-
}
- }
分享文章:二进制字符串相加
文章链接:http://ybzwz.com/article/jojdhp.html