Human Cyborg Relations - 1 year ago 85
Java Question

# Adding numbers which are stored in string variables

Given two non-negative numbers num1 and num2 represented as strings, return the sum of num1 and num2.

The length of both num1 and num2 is less than 5100.

Both num1 and num2 contain only digits 0-9.

Both num1 and num2 do not contain any leading zeros.

You must not use any built-in BigInteger library or convert the inputs to integer directly.

I tried my solution but it doesn't work. Suggestions?

``````public class Solution {
public String addStrings(String num1, String num2) {
double multiplier = Math.pow(10, num1.length() - 1);
int sum = 0;

for (int i = 0; i < num1.length(); i++){
sum += ((((int) num1.charAt(i)) - 48) * multiplier);
multiplier /= 10;
}

multiplier = Math.pow(10, num2.length() - 1);

for (int i = 0; i < num2.length(); i++){
sum += ((((int) num2.charAt(i)) - 48) * multiplier);
multiplier /= 10;
}

return "" + sum;
}
}
``````

An `int` (your `sum` variable) cannot hold values like that. `BigInteger` can, but you're not allowed to use it.
Since the sum will be at least the number of digits of the longest input value, and may be one longer, you should allocate a `char[]` of length of longest input plus one. When done, construct final string using `String(char[] value, int offset, int count)`, with an offset of 0 or 1 as needed.