How do you add a number of any length in Java which are strings without BigInteger?
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
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'.
hoiberg (December 16th, 2010)
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