here's JAVA solution, without using linked list. The idea is simple and straightforward. when adding two binary digits, if both are 1 memorize 1 and drop down 0. if memorized element is 1, and both elements are 1, drop down 1, memorize one. Otherwise drop down the number and memorized elements is 0. ctoi is additional function to convert char into int.
public class Solution
{
int ctoi(char c)
{
switch(c)
{
case '0': return 0;
case '1': return 1;
default: return -1;
}
}
String add(String s1, String s2)
{
StringBuffer sb1 = new StringBuffer(s1);
StringBuffer sb2 = new StringBuffer(s2);
StringBuffer sb3 = new StringBuffer();
while (sb1.length() != sb2.length())
{
if (sb1.length()<sb2.length())
sb1.insert(0,"0");
else
sb2.insert(0,"0");
}
int r=0, size = sb1.length();
char c;
for (int i=size-1; i>=0; i--)
{
int sum = ctoi(sb1.charAt(i)) + ctoi(sb2.charAt(i)) + r;
if (sum == 3) {c = '1'; r = 1;}
else if (sum == 2) {c = '0'; r = 1;}
else if (sum == 1) {c = '1'; r = 0;}
else if (sum == 0) {c = '0'; r = 0;}
else { c = '\0'; r = 0; } //this part is for error handling
sb3.insert(0, c);
}
if (r == 1) sb3.insert(0, "1");
return sb3.toString();
}
public String addBinary(String a, String b)
{
return add(a, b);
}
}