What is the best way to compare two very large numbers contained in string literals?
For example I want to compare the followings: "90000000000000000000000000000000000000000000000000000000000000000000000000001" "100000000000000000000000000000000000000000000000000000000000000000000000000009"
or
"0000000000111111111111111111111111111111111111111111111111111111111111111111" "0000001111111111111111111111111111111111111111111111111111111111111111111111"
In both cases obviously the second one is greater, but how could I find it out efficiently without iterating on elements?
I would personally take the simplest approach: use
BigInteger
to parse both values, and compare those results. That wouldn't be terribly efficient, but it would be very simple - and then you could benchmark to see whether it's fast enough.Otherwise, you could find the effective length by ignoring leading zeroes - and if one number is longer than the other, then that's all you need to know. Or write a method to get the "effective" digit of a string which may be shorter, returning 0 if necessary, and then compare from the longer string's length downwards until one string gives a bigger value. Something like:
Note that this doesn't check that it's a valid number at all, and it definitely doesn't attempt to handle negative numbers.
Here is another solution:
If by comparison you mean boolean check, this will work: