二进制求和
2019-01-27 本文已影响0人
小白学编程
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
转为数字的方法,数值特别大的情况会有溢出
class Solution {
public String addBinary(String a, String b) {
int len1 = a.length();
int len2 = b.length();
double sum1 = 0;
double sum2 = 0;
double count = 0;
for (int i = len1 - 1; i >= 0; i--) {
if (a.charAt(i) == '1') {
double temp = Math.pow(2, count);
sum1 += temp;
}
count++;
}
System.out.println(sum1);
count = 0;
for (int j = len2 - 1; j >= 0; j--) {
if (b.charAt(j) == '1') {
double temp = Math.pow(2, count);
sum2 += temp;
}
count++;
}
System.out.println(sum2);
double sum = 0;
sum = sum1 + sum2;
if (sum == 0) {
return "0";
}
StringBuffer result = new StringBuffer("");
while (sum != 1) {
if (sum % 2 == 0) {
result.append("0");
} else {
result.append("1");
}
sum = (int)sum / 2;
}
result.append("1");
return result.reverse().toString();
}
}
class Solution {
public String addBinary(String a, String b) {
//0 + 1 = 1; 0 + 0 = 0; 1 + 1 = 10(进位)
int lenA = a.length();
int lenB = b.length();
int i = lenA - 1 , j = lenB - 1;
String result = "";
int carry = 0;//进位
while (i >= 0 || j >= 0) {
int tempA, tempB;
if (i >= 0) {
tempA = a.charAt(i) - '0';
i--;
} else {
tempA = 0;
}
if (j >= 0) {
tempB = b.charAt(j) - '0';
j--;
} else {
tempB = 0;
}
int sum = tempA + tempB + carry;
result = sum % 2 + result;
carry = sum / 2;
}
if (carry > 0) {
result = '1' + result;
}
return result;
}
}
将String换为StringBuilder,速度明显提升
class Solution {
public String addBinary(String a, String b) {
//0 + 1 = 1; 0 + 0 = 0; 1 + 1 = 10(进位)
int lenA = a.length();
int lenB = b.length();
int i = lenA - 1 , j = lenB - 1;
StringBuilder result = new StringBuilder("");
int carry = 0;//进位
while (i >= 0 || j >= 0) {
int tempA, tempB;
if (i >= 0) {
tempA = a.charAt(i) - '0';
i--;
} else {
tempA = 0;
}
if (j >= 0) {
tempB = b.charAt(j) - '0';
j--;
} else {
tempB = 0;
}
int sum = tempA + tempB + carry;
result.append(sum % 2);
carry = sum / 2;
}
if (carry > 0) {
result.append('1');
}
return result.reverse().toString();
}
}