Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
a =
"11"
b =
"1"
Return
"100"
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package leetcode; | |
/** | |
* | |
* Solution: Same to Add Two Number but there's a lot of useful tips not very easy to handle. | |
* 1. Need to identify which string is shorter.(Make sure a is longer, if not, swap) --> only judge once aIndex >= 0 | |
* 2. Concatenate result using string make is easier and don't need to consider boundary and shift. | |
* | |
* Similiar Question: Add Two number | |
* @author jeffwan | |
* @date Apr 1, 2014 | |
*/ | |
public class AddBinary { | |
public String addBinary(String a, String b) { | |
if (a.length() < b.length()) { | |
String temp = a; | |
a = b; | |
b = temp; | |
} | |
int aIndex = a.length() - 1; | |
int bIndex = b.length() - 1; | |
int carry = 0; | |
String result = ""; | |
while(bIndex >= 0) { | |
int sum = carry + Character.getNumericValue(a.charAt(aIndex)) | |
+ Character.getNumericValue(b.charAt(bIndex)); | |
result = String.valueOf(sum % 2) + result; | |
carry = sum / 2; | |
aIndex--; | |
bIndex--; | |
} | |
while(aIndex >=0) { | |
int sum = carry + Character.getNumericValue(a.charAt(aIndex)); | |
result = String.valueOf(sum % 2) + result; | |
carry = sum / 2; | |
aIndex--; | |
} | |
if (carry != 0) { | |
result = String.valueOf(carry) + result; | |
} | |
return result; | |
} | |
/** | |
* My solution transfer String to Int is dangerous, it faces many problems like Integer Boundary. | |
* Easiest way is to operate char or string directly. | |
* Failed Test case: "1110110101", "1110111011" Output: "2147483647" Expected:"11101110000" | |
*/ | |
public String addBinary2(String a, String b) { | |
int carry = 0; | |
int result = 0; | |
int i = a.length() - 1, j = b.length() - 1; | |
int flag = 0; | |
for (; i >= 0 && j >= 0; i--, j--) { | |
int aNum = Character.getNumericValue(a.charAt(i)); | |
int bNum = Character.getNumericValue(b.charAt(j)); | |
int sum = aNum + bNum + carry; | |
result += sum % 2 * Math.pow(10, flag); | |
carry = sum / 2; | |
flag++; | |
} | |
while (i >= 0) { | |
int sum = carry + Character.getNumericValue(a.charAt(i)); | |
result += sum % 2 * Math.pow(10, flag); | |
carry = sum / 2; | |
flag++; | |
i--; | |
} | |
while (j >= 0) { | |
int sum = carry + Character.getNumericValue(b.charAt(j)); | |
result += sum % 2 * Math.pow(10, flag); | |
carry = sum / 2; | |
flag++; | |
j--; | |
} | |
if (carry != 0) { | |
result += Math.pow(10, flag); | |
} | |
return String.valueOf(result); | |
} | |
} |
No comments:
Post a Comment