1 answer

Dynamic Implementation of Stack - The purpose is to use our dynamic implementation of stack. The...

Question:

Dynamic Implementation of Stack -

The purpose is to use our dynamic implementation of stack. The application will be to add large numbers.

Review adding large numbers

Remember that we can use stacks to safely add integer values that overflow the int data type

  • g. in Java, the maximum possible int value Integer.MAX_VALUE is:
    2147483647
  • so any int addition larger than this will overflow and fail

Using stacks to add large numbers safely

Will actually represent the large integers to be added as strings of characters, to avoid any overflow problems here. Then will use three(!) stacks of datatype Integer to do the addition safely.

The idea is to add each pair of digits from the numbers, from right to left. The units part of this total is pushed to the results stack, the tens part is the carry digit, added in to the next pair.

The addition algorithm in pseudocode is something like:

//push digits from numbers into stacks in appropriate order loop for the digits in the first number     push digit to first stack loop for the digits in the second number     push digit to second stack //pop stacks, add digits and push result to result stack.  Careful with carry while (!stacks are empty)     pop digits from stacks and add     push units part to result stack     tens part is the carry to be added in next iteration //print the result from the result stack while (!result stack is empty)     pop result stack

Open the project and see Tester::main(). You must write code in the Tester::main() method that uses the stack implementation to add the pairs of numbers given.

Format your output so that it shows the first and second numbers, and your result (I've used '?' below to show where your result will go). Run your program three times to test each of the pairs of numbers provided e.g.

1 + 2147483647 = ?  2147483647 + 1 = ?  2147483647 + 2147483647 = ?

public class Tester
{
public static void main()
{
//first shorter
String first = "1";
String second = "2147483647";

//second shorter
//String first = "2147483647";
//String second = "1";

//same length
//String first = "2147483647";
//String second = "2147483647";
  
//you must write all of your code here }
}

public class StackUnderflowException extends RuntimeException
{
public StackUnderflowException()
{
super();
}

public StackUnderflowException(String message)
{
super(message);
}
}

public class LinkedStack<T> implements StackInterface<T>
{
private Item<T> top;

public LinkedStack()
{
top = null;
}

public void push(T element)
{
Item<T> item = new Item<T>(element);

if (!isEmpty())
item.next = top;

top = item;
}

public T pop() throws StackUnderflowException
{
if (isEmpty())
throw new StackUnderflowException("Pop attempted on empty stack");
else {
T info = top.info;
top = top.next;
return info;
}
}

public boolean isEmpty()
{
return top == null;
}
}

public interface StackInterface<T>
{
void push(T element);

T pop() throws StackUnderflowException;

boolean isEmpty();
}

public class Item<T>
{
protected T info;
protected Item<T> next;

public Item()
{
info = null;
next = null;
}

public Item(T info)
{
this.info = info;
next = null;
}
}


Answers

:: solution ::

public static void main(String []args){         String first = "2147483647";         String second = "2147483647";                  Stack<Integer> stack1 = new Stack<>();         Stack<Integer> stack2 = new Stack<>();                  int len1 = first.length();         int len2 = second.length();                  int duplen1 = len1;         int duplen2 = len2;         while(len1>0 || len2>0){                 if(len1>0){                         stack1.push(first.charAt(duplen1-len1)-'0');                         len1--;                 }                 if(len2>0){                         stack2.push(second.charAt(duplen2-len2)-'0');                         len2--;                 }         }                  String res = "";                  int carry = 0;         while(!stack1.isEmpty() || !stack2.isEmpty()){                 int firstDigit = (stack1.isEmpty())?0:stack1.pop();                 int secondDigit = (stack2.isEmpty())?0:stack2.pop();                 if(carry+firstDigit+secondDigit >= 10){                         res = (carry+firstDigit+secondDigit-10)+res;                         carry = 1;                 }                 else{                         res = (carry+firstDigit+secondDigit)+res;                         carry = 0;                 }         }         if(carry==1){                 res = 1+res;         }                  System.out.println("sum of numbers "+first+" and "+second+" = "+res); }

</> Online Java Compiler - Online Jax + X ... f → CO tutorialspoint.com/compile_java_online.php codingground Compile and Exec</> Online Java Compiler - Online Jax + X ... CO tutorialspoint.com/compile_java_online.php codingground Compile and Execute</> Online Java Compiler - Online Jax + X ... CO tutorialspoint.com/compile_java_online.php codingground Compile and Execute

I have provide you the main function with code.

And also provided the screenshots of the inputs you provided for testing.

Hope you like it.

.

Similar Solved Questions

1 answer
11.57 on Instrumentation and Measurement (Direct, Fast, and Accurate Measurement of VT arnd K of MOS...
11.57 on Instrumentation and Measurement (Direct, Fast, and Accurate Measurement of VT arnd K of MOS Transistor Using r Sift Circuit, 1991, Vol. 40, pp. 951-955) described the use of a simple linear rearession model to express drairn current y in milliamperes) as a function af ground-to-source volta...
1 answer
Consider a bond with the following characteristics: Semi-annual payments, coupon rate of 8%, $1,000 par value....
Consider a bond with the following characteristics: Semi-annual payments, coupon rate of 8%, $1,000 par value. 6 years to maturity. Discount rate (Interest rate) is r= 5%. If 95 days have passed since the last coupon payment, what is the accrued interest? Consider 182 days between payments. a) Calcu...
1 answer
When testing the hypothesized difference between two population means, the implied hypothesis is H0: µ1 =...
When testing the hypothesized difference between two population means, the implied hypothesis is H0: µ1 = 0 H0: µ1 - µ2 = 0 H0: µ2 = 0 H0: µ1 - µ2 ≠ 0...
1 answer
Discuss how the Supreme Court has used the Fourteenth Amendment to apply the Bill of Rights...
Discuss how the Supreme Court has used the Fourteenth Amendment to apply the Bill of Rights to the States....
1 answer
The authors of a paper titled "Age and Violent Content Labels Make Video Games Forbidden Fruits...
The authors of a paper titled "Age and Violent Content Labels Make Video Games Forbidden Fruits for Youth" carried out an experiment to determine if restrictive labels on video games actually increased the attractiveness of the game for young game players. Participants read a description of...
1 answer
Please help with this problem Ext-2.2 (35 points) An insulated, rigid tank is divided into two...
please help with this problem Ext-2.2 (35 points) An insulated, rigid tank is divided into two compartments by a frictionless, thermally conducting piston. One compartment initially contains 0.6 m' of saturated water vapor at 200 °C and the other compartment contains 0.8 m' of superhe...
1 answer
Consider a disc of radius R centered the origin in space and rotating about the z...
Consider a disc of radius R centered the origin in space and rotating about the z axis in some inertial reference frame O. (a) What is the maximum angular velocity w of the disc allowed by Special Relativity? Recall angular velocity is 2 times the number of rotations per second. (b) Consider an obse...
1 answer
The description of a cell energy process is listed below. . produces carbon dioxide .occurs in...
The description of a cell energy process is listed below. . produces carbon dioxide .occurs in a cell's mitochondria involves the formation of the electron carriers NADH and FADHa produces a small amount of ATP Which process is described? o the electron transport chain O glycolysis O the citric ...
1 answer
Need help 3. For the circuit given, determine the average power dissipated in the 100 k2...
need help 3. For the circuit given, determine the average power dissipated in the 100 k2 resistor. (5 pts) 100 S2 1:10 + w 50 V rms V2 100 k2...
1 answer
I am new to Python and am having trouble coming up with writing code to the...
I am new to Python and am having trouble coming up with writing code to the following problem... The program must: Prompt for a file name Opens that file and reads through the file Displays a custom error message if the file does not exist You can pull the hour out from the 'From ' line by ...
1 answer
Fourteen different second-year medical students at a hospital measured the blood pressure of the same person....
Fourteen different second-year medical students at a hospital measured the blood pressure of the same person. The systolic readings (mm Hg) are listed below. Use the given data to construct a boxplot and identify the 5-number summary. 124 132 135 R 139 139 120 120 125 125 135 135 130 145 R 134 140 1...
1 answer
A firm has a return on equity of 23 percent. The total asset turnover is 2.2...
A firm has a return on equity of 23 percent. The total asset turnover is 2.2 and the profit margin is 6 percent. The total equity is $5,600. What is the net income? Multiple Choice $739 $2,834 $336 $1,288 $585...
1 answer
16.10 A sluice across a channel om wide discharges a stream 1.2 m deep. What will...
16.10 A sluice across a channel om wide discharges a stream 1.2 m deep. What will be the tow if the upstream depth is om? The conditions downstream cause an hydraulic jump to occur at a place where concrete blocks have been placed in the bed. What will be the force on the blocks if the downstream de...
1 answer
Refer to Exhibit 19-7. Which of the graphs shows a perfectly elastic demand curve? A. (1)...
Refer to Exhibit 19-7. Which of the graphs shows a perfectly elastic demand curve? A. (1) B. none of these options C. (2) D. (3) and (4) Price 2 - X 0 1000 Quantity (1) 1000 Quantity 100 Quantity (3) 0100 Quantity (4)...