Java Program to Subtract Two Numbers using Linked Lists

«
»
This is a Java Program to subtract two large numbers using Linked List. A linked list is a data structure consisting of a group of nodes which together represent a sequence. Under the simplest form, each node is composed of a data and a reference (in other words, a link) to the next node in the sequence. This structure allows for efficient insertion or removal of elements from any position in the sequence.
Maximum value that can be stored in the primitive datatypes ‘int’ and ‘long’ is 231 and 263 respectively. Hence values larger than this cannot be represented using int or long. An alternative is to use the BigInteger class which is available in java as java.math.BigInteger . However, here we will be applying concepts of linked lists to subtract very large numbers.

Here is the source code of the Java program to subtract two large numbers using Linked List. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. /*
  2.  *  Java Program to subtract two large numbers using Linked Lists
  3.  */
  4.  
  5. import java.util.*;
  6.  
  7. public class SubtractLargeNumbersUsingLinkedLists
  8. {
  9.     public static void main(String[] args)
  10.     {
  11.         Scanner scan = new Scanner(System.in);
  12.         /* Create Linked Lists */
  13.         LinkedList<Integer> num1 = new LinkedList<Integer>();
  14.         LinkedList<Integer> num2 = new LinkedList<Integer>();
  15.         LinkedList<Integer> ans = new LinkedList<Integer>();
  16.         LinkedList<Integer> tmp = new LinkedList<Integer>();
  17.         /* Accept numbers */
  18.         System.out.println("Subtracting Large Numbers Using Linked Lists Test\n");
  19.         System.out.println("Enter number 1");
  20.         String str1 = scan.next();
  21.         System.out.println("Enter number 2");
  22.         String str2 = scan.next();
  23.         /* Find larger number */
  24.         int l1 = str1.length(), l2 = str2.length();
  25.         String s1 = str1, s2 = str2;
  26.         boolean sign = false;
  27.         if (l1 < l2 || (l1 == l2 && str1.compareTo(str2) < 0))
  28.         {
  29.             s1 = str2;
  30.             s2 = str1;
  31.             sign = true;
  32.         }
  33.         l1 = s1.length();
  34.         while (s2.length() != l1)
  35.             s2 = "0" + s2;
  36.         /* Store digits in lists */            
  37.         for (int i = l1 - 1; i >= 0; i--)
  38.         {
  39.             num1.add(s1.charAt(i) - '0');
  40.             /* 9 complement of second number */
  41.             num2.add('9' - s2.charAt(i));
  42.         }    
  43.         /* Add the numbers */        
  44.         int carry = 0;
  45.         for (int i = 0; i < l1; i++)
  46.         {
  47.             int d1 = 0, d2 = 0;            
  48.             try {
  49.                 d1 = num1.get(i);
  50.             } 
  51.             catch(Exception e){}            
  52.             try {
  53.                 d2 = num2.get(i);
  54.             } 
  55.             catch(Exception e){}                        
  56.             int x = d1 + d2 + carry;
  57.             tmp.add(x % 10);
  58.             carry = x / 10;
  59.         }
  60.         /* Adding carry and storing in ans list*/
  61.         for (int i = 0; i < l1; i++)
  62.         {
  63.             int x = tmp.get(i) + carry;
  64.             ans.add(x % 10);
  65.             carry = x / 10;
  66.         }    
  67.         /* Print number */    
  68.         System.out.print("\nDifference = ");
  69.         if (s1.equals(s2))
  70.             System.out.print("0\n");
  71.         else
  72.         {
  73.             if (sign)
  74.                 System.out.print("-");
  75.             /* Dont print leading zeroes */
  76.             int i;
  77.             for (i = ans.size() - 1; i >= 0; i--)
  78.                 if (ans.get(i) != 0)
  79.                     break;
  80.             for (; i >= 0; i--)
  81.                 System.out.print(ans.get(i));
  82.             System.out.println();
  83.         }                
  84.     }
  85. }

advertisement
Subtracting Large Numbers Using Linked Lists Test
 
Enter number 1
9456738572365648932758346782759273576
Enter number 2
56736823748726353476582734827356545368752365
 
Difference = -56736814291987781110933802069009762609478789
 
 
 
Subtracting Large Numbers Using Linked Lists Test
 
Enter number 1
83657367648164375237587648523823975867384567263847286325673682366458782936575682
36572582365783465764756873456765826382758265784685627365826375836576572863872655
 
Enter number 2
23647236572638468364732576823748726573687273567283689587364723564586458287578263
86836827563287526582786235723878364738568745862358293576548237582365758781878286
 
 
Difference = 6001013107552590687285507170007524929369729369656359673830895880187
23246489974184973575480249593918197063773288746164418951992232733378927813825421
0814081994369
 
 
Subtracting Large Numbers Using Linked Lists Test
 
Enter number 1
83748562837562383475628737416872984236198927419812347652388735823741846283754568
27938757268728382365872562837842356872957826874236547375235627947238562794783567
53562377826357197843587645728738523657327471874678456382749836435728974816423653
2342357726378462378672357
Enter number 2
23785623874816487638672368926572358263756837435767555535238568278623758758263857
65846578384573846587657628387648523758273562386237652736486385792719281019018408
29347293758465832701801030812498357801981974384917417418924787329561727418578652
8736582735826353765198481647358365273958635759727385671
 
Difference = -237856238748164876386723689264886097009192750522919267978216952943
87559830844045310813395109914724030292529308205850010048340038717801736485434358
46323192144171746097701956711088455215524557447954241556171870738297731960488059
043999467039744172755237461996475450317410826022916232257297348713314

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.