Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two large numbers

Tags:

java

compare

Two strings representing two numbers have been provided as input. The numbers in the string can be so large that they may not be represented by the Java data type int. The objective is to compare the two numbers and output that number as a string

for example we have to compare:

"874986754789289867753896798679854698798789857387687546456"

and

"98347598375689758967756458678976893478967586857687569874"

which both are out of range of long and int data types in JAVA and after comparing we have to output that number as a string

like image 258
Akshay Sharma Avatar asked May 17 '26 07:05

Akshay Sharma


2 Answers

you could start by first looking at each string's length. if one of them is longer and you know they are both unsigned values, the longer string has the bigger number. if they both have the same length, you start comparing the strings char by char starting from left to right. when you found your first bigger digit you conclude that number is bigger.

like image 101
gpu3d Avatar answered May 18 '26 21:05

gpu3d


Whether you're trying to compare or subtract isn't clear, but Java's BigInteger class has both operations. This is probably what you need:

BigInteger a = new BigInteger("874986754789289867753896798679854698798789857387687546456");
BigInteger b = new BigInteger("98347598375689758967756458678976893478967586857687569874");

System.out.println( (a.compareTo(b) > 0 ? "a" : "b") + " is larger.");

If you need to subtract the numbers I'd definitely use BigInteger, but if all you need to do is compare them you could write your own method. One of your input strings is longer than the other, so barring leading zeroes that would tell you right away which is larger. If the strings are the same length you could compare them character by character in a loop to see which is larger. The String charAt and toCharArray methods give you two different ways to implement this approach.

like image 31
Bill the Lizard Avatar answered May 18 '26 21:05

Bill the Lizard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!