You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
2.1 KiB

// The StackApps class that implements two Stack applications
// Your name here
import java.util.Scanner;
public class StackApps
{
// convert a decimal number into a binary number and save it in a stack
// Do not create any arrays! Do not use any Java libraries to do the convertion.
// Doing so will result in points deduction.
public String decToBin(int numDec)
{
CharStack stackBinary = new CharStack(64); // stack used to store the result binary number
while (numDec > 0) {
if (numDec % 2 == 0)
stackBinary.push('0');
else
stackBinary.push('1');
numDec /= 2;
}
return stackBinary.toString(); // return a string representation of the stack
}
// compute the sum of the two big intergers and save the result in a stack
// Do not create any arrays! Do not use any Java libraries to do the calculation.
// Doing so will result in points deduction.
public String addBigIntegers(String num1, String num2)
{
CharStack stackNum1 = new CharStack(64); // stack used to store number 1
CharStack stackNum2 = new CharStack(64); // stack used to store number 2
CharStack stackResult = new CharStack(64); // stack used to store the result of the addition
CharStack remaining;
for (int i = 0; i < num1.length(); i += 1)
stackNum1.push(num1.charAt(i));
for (int i = 0; i < num2.length(); i += 1)
stackNum2.push(num2.charAt(i));
int carry = 0;
int a;
int b;
int result;
while (!(stackNum1.isEmpty() || stackNum2.isEmpty())) {
a = (int) (stackNum1.pop() - '0');
b = (int) (stackNum2.pop() - '0');
result = (a+b+carry);
carry = result/10;
stackResult.push((char)((result%10) + '0'));
}
if (stackNum1.isEmpty())
remaining = stackNum2;
else
remaining = stackNum1;
while (!(remaining.isEmpty())) {
a = (int) (remaining.pop() - '0');
result = (a+carry);
carry = result/10;
stackResult.push((char)((result%10) + '0'));
}
if (carry > 0)
stackResult.push((char)(carry + '0'));
return stackResult.toString(); // return a string representation of the stack
}
}