Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
792 views
in Technique[技术] by (71.8m points)

Java: Adding large numbers without using BigInteger

I have looked at the other examples of these questions asked on this website, but they are all quite more complex than I know how to deal with and use. Basically, how do I sum large numbers, or even store large numbers to sum them later, without the use the of BigInteger class? The numbers are so large they won't even fit into long.

The idea I have now is to use a character array, but I have no idea how to to addition with super large numbers even if I am able to store the numbers in a character array. Any help would be great. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Suppose you store a huge number in an array of longs. Then all you need to do is to add each pair up, detect whether there is overflow, then add one to the next pair. This is exactly like how we actually do addition by hand. Suppose we want to compute:

 5879
+6843

What we do is we add 9 and 3 together, it overflows and becomes 2. We then add 7 and 4, and add one from the overflow to get 2. We again overflow. Next we add 8 and 8 + 1 for overflow to get 7, again with overflow. Finally we add 5 and 6 + 1 for overflow to get 2 with overflow. We thus get 12722. Now imagine each of those digits are a long in your array.

To detect overflow: if you have two positive numbers, when added together they produce a negative number only when they overflowed. So you just need to check whether result is less than 0 to detect whether you need to add one to the next pair.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...