How do you add a number of any length in Java which are strings without BigInteger?
Printable View
How do you add a number of any length in Java which are strings without BigInteger?
The same way you add numbers by hand: starting from right to left, take a digit, then add it to a number in the same digit location. If you need to carry, put a carry for the next number. Repeat until there are no more digits left.
Would you have any idea how to put that into code at all?
I won't do all the work for you, but I will give you some hints.
You can get a character from a String using the charAt() method. This will give you the character at a specific index. Note that the index 0 is the furthest left number, and as with Java array indices the last index is String.length() - 1.
Once you have the character, it will likely be a unicode value representing '0'..'9'. The actual values are different than 0..9 (notice the subtle difference). Before you perform the addition, you must subtract off the offset for '0' (this works because'0'..'9' are all consecutive codes and in increasing order). Before writing to your output string you must first determine if you need to carry (if the result came out to be greater than 10), and then subtract that off before re-adding the offset '0'.
Well I guess my question is how would I implement it. Like the carrying the 1 would have to be in an if statement. Also what kind of loop would the Char.at be in?
Did you not like the identical answer you got in your other post?
http://www.javaprogrammingforums.com...ssignment.html