Human Cyborg Relations - 6 months ago 48

Java Question

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;

}

}

Answer

You must notuse any built-in BigInteger library orconvert the inputs to integerdirectly.

Note that you are adding two integers of **up to 5100** digits each. That is not that max *value*, but the max *number of digits*.

An `int`

(your `sum`

variable) cannot hold values like that. `BigInteger`

can, but you're not allowed to use it.

So, **add the numbers like you would on paper**: Add last digits, write lower digit of the sum as last digit of result, and carry-over a one if needed. Repeat for second-last digit, third-last digit, etc. until done.

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.