Question

I only need help with the constructors and add method. Thanks!

Background Arbitrary length integers are integers that have no size restriction. Recall that the int type has a range of -2,147,483,648 to 2,147,483,647. The long type runs from -263 to 263 - 1. Sometimes these numbers are not large enough. One example application that may need larger numbers is public-key cryptography where very large integers are used to make decryption hard. A large integer may be represented as a linked list by storing each digit in a node and linking the digits together in the correct sequence. For example, the number 45341 would be represented by the list [4, 5, 3, 4, 1 Details Implement a class called LinkedLargeInteger. LinkedLargeIntegers are to be immutable. LinkedL,argeInteger is to have the following methods. (Note: Java has a BigInteger class for this, implemented using an array rather than a linked list. You are not to use it You are not to use any of the Java Collections Framework for this assignment. You are to implement your linked list directly Begin by writing an interface called LargeInteger that specifies these public methods LinkedLargeInteger will then implement the LargeInteger interface. You need only handle non-negative numbers for this assignment 1. constructor - takes a String representing the large number and creates the linked represen tation. 2. constructor - takes an int representing the large number and creates the linked representa- tion 3. constructor - takes a long representing the large number and creates the linked representa- tion 4. add - takes a LinkedL,argeInteger; returns the LinkedLargeInteger sum of this and the argument 5. subtract - takes a LinkedLargeInteger; returns the LinkedLargeInteger difference of this and the argument 6. multiply - takes a LinkedLargeInteger; returns the LinkedLargeInteger product of this and the argument 7. compareTo - takes an Object; returns 1 if this is greater than the argument, 0 if they are equal, and -1 if this is less than the argument. Recall that this means LargeInteger will extend the Comparable interface 8. equals 9. hashCode 10. toString You might find it helpful to create two LinkedLargeInteger constants ZERO and ONE. Write a main method to test your code. Test your code

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the code below:

LinkedLargeInteger.java

package classes13;

public class LinkedLargeInteger{

public class ListNode {

public int data;

public ListNode next;

public ListNode(int data) {

this.data = data;

this.next = null;

}

public ListNode(int data, ListNode next) {

this.data = data;

this.next = next;

}

}

private ListNode front; // refers to first node in list (null if empty)

public String thisString;

private int index = 0;

public LinkedLargeInteger(String s) {

thisString = s;

front = null; // null front means empty

int l1 = s.length();   

for (int i = l1 - 1; i >= 0; i--)

add(s.charAt(i) - '0');

}

public void add(int value) {

if (index == 0) {

// insert at the front

front = new ListNode(value, front);

} else {

// insert in middle/end; walk to node before the one to insert

ListNode current = goTo(index - 1);

ListNode newNode = new ListNode(value, current.next);

current.next = newNode;

}

index++;

}

public int get(int index) {

ListNode current = goTo(index);

return current.data;

}

public int size() {

int count = 0;

ListNode current = front;

while (current != null) {

current = current.next;

count++;

}

return count;

}

private ListNode goTo(int index) {

ListNode current = front;

for (int i = 0; i < index; i++) {

current = current.next;

}

return current;

}

LinkedLargeInteger add(LinkedLargeInteger num2){

int l1 = thisString.length();

LinkedLargeInteger ans = new LinkedLargeInteger("");

int l2 = num2.thisString.length();

int len = l1 > l2 ? l1 : l2;

int carry = 0;

for (int i = 0; i < len; i++)

{

int d1 = 0, d2 = 0;   

try {

d1 = get(i);

}

catch(Exception e){}   

try {

d2 = num2.get(i);

}

catch(Exception e){}   

int x = d1 + d2 + carry;

ans.add(x % 10);

carry = x / 10;

}

/* Adding carry */

while (carry != 0)

{

ans.add(carry % 10);

carry /= 10;

}

return ans;

}

}

LinkedLargeIntegerTester.java

package classes13;

/*

* Java Program to add two large numbers using Linked List

*/

import java.util.Scanner;

public class LinkedLargeIntegerTester

{

public static void main(String[] args)

{   

Scanner scan = new Scanner(System.in);

/* Create Linked Lists */

/* Accept numbers */

System.out.println("Adding Large Numbers Using Linked Lists Test\n");

System.out.println("Enter number 1");

String s1 = scan.next();

System.out.println("Enter number 2");

String s2 = scan.next();

/* Store digits in lists */

LinkedLargeInteger num1 = new LinkedLargeInteger(s1);

LinkedLargeInteger num2 = new LinkedLargeInteger(s2);

LinkedLargeInteger ans = num1.add(num2);

System.out.print("\nSum = ");

for (int i = ans.size() - 1; i >= 0; i--)

System.out.print(ans.get(i));

System.out.println();   

}

}

output:

やや Quick Access Console 3 fill inated> LinkedLargelntegesterava Application] CAProgram Files Javare7binljavaw.exe (Dec 6, 2018, 10:30:53 AM) Adding Large Numbers Using Linked Lists Test Enter number 1 1234567898765432123456789 Enter number 2 12345678987654321234567890876543212345678909876543212345678 Sum = 12345678987654321234567890876543213580246808641975335802467

Add a comment
Know the answer?
Add Answer to:
I only need help with the constructors and add method. Thanks! Background Arbitrary length integers are...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • DESCRIPTION: The range of integers that can be represented in Java using a primitive data type is...

    DESCRIPTION: The range of integers that can be represented in Java using a primitive data type is only from-263 to 263-1. What if we need to manipulate integer values beyond this range? In this assignment you will write a HugeInteger class which is able to represent arbitrar- ily large integer numbers. This class must implement arithmetic operations on integers such as addition, subtraction, multiplication, division and comparison. You have to implement this class without using Java predefined classes, unless specified...

  • F# ONLY SOMEONE SOLVED IN PYTHON JUST NOW. I NEED F SHARP PROGRAMMING THANKS A more...

    F# ONLY SOMEONE SOLVED IN PYTHON JUST NOW. I NEED F SHARP PROGRAMMING THANKS A more efficient version of the function for computing Tetranacci numbers can be defined by following three steps: Implement a function which takes a list of integers and adds the sum of the top four elements to the head of the list (e.g., in F#, 1::1::1::1::[] should become 4::1::1::1::1::[]). Implement a recursive function which accepts an integer n as input (again, assume n >= 0), and...

  • *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods...

    *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods that has the following generic methods: (1) Write the following method that returns a new ArrayList. The new list contains the nonduplicate (i.e., distinct) elements from the original list. public static ArrayList removeDuplicates(ArrayList list) (2) Write the following method that shuffles an ArrayList. It should do this specifically by swapping two indexes determined by the use of the random class (use Random rand =...

  • I need help Writing a Python code!!! Implement an ordered list using doubly linked list Implement...

    I need help Writing a Python code!!! Implement an ordered list using doubly linked list Implement the following operations for an ordered list of integers ordered in ascending order using a doubly linked list. The “head” of the list be where the “smallest items are and let “tail” be where the largest items are. You may use whatever mechanism you like to keep track of the head and tail of the list. E.g. references or sentinel nodes. • OrderedList ()...

  • I really need help with this python programming assignment Program Requirements For part 2, i need...

    I really need help with this python programming assignment Program Requirements For part 2, i need the following functions • get floats(): It take a single integer argument and returns a list of floats. where it was something like this def get_floats(n):   lst = []   for i in range(1,n+1):     val = float(input('Enter float '+str(i)+': '))     lst.append(val)   return lst • summer(): This non-void function takes a single list argument, and returns the sum of the list. However, it does not use...

  • In this assignment, you are asked to implement a Java class named HugeInt for storing huge...

    In this assignment, you are asked to implement a Java class named HugeInt for storing huge integers and performing mathematical operations on them. This class must have a private variable of type LinkedList〈Byte〉 which stores digits of a huge integer and ten of the following public methods (choose ten methods out of 12): public void setValue (int value): gets an integer (like 1234) as input parameter and stores its digits in the linked list in the same order as they...

  • can i please get help on this? i don't know how to do it and I'm...

    can i please get help on this? i don't know how to do it and I'm so confused. This is in java. This is what I need to do. Thank you so much. In this lab assignment, you are to write a class IntegerSet that represents a set of integers (by definition, a set contains no duplicates). This ADT must be implemented as a singly linked list of integers (with no tail reference and no dummy head node) , but...

  • I need the following written in Java please, thank you ' We want you to implement...

    I need the following written in Java please, thank you ' We want you to implement a java class that will show details on users and throw exceptions where needed. The following requirements specify what fields you are expected to implement in your User class: - A private String firstName that specifies the first name of the user - A private String lastName that specifies the last name of the user - A private int age that specifies user's age...

  • I need a python 3 help. Please help me with this question Part 2. Linked Lists...

    I need a python 3 help. Please help me with this question Part 2. Linked Lists You start working with the class LinkNode that represents a single node of a linked list. It has two instance attributes: value and next. class LinkNode: def __init__(self,value,nxt=None): assert isinstance(nxt, LinkNode) or nxt is None self.value = value self.next = nxt Before you start with the coding questions, answer the following questions about the constructor Valid Constructor or Not? LinkNode(1, 3) LinkNode(1, None) LinkNode(1,...

  • please help me with this in C# language. Constructors The goal for this exercise is to...

    please help me with this in C# language. Constructors The goal for this exercise is to understand what constructors are, how to define them, and how to call them, including ‘default’ constructors, and including the use of overloading to provide multiple constructors. One of the advantages of having a clear separation between the public interface of an object and private internal implementation of an object is that once you've got the data in the object you can then ask the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT