diff --git a/.gitignore b/.gitignore index 5041262..cc1d35e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ *.dat *.class /TAGS +*.txt diff --git a/StackApps.java b/StackApps.java index 22997ea..99021c1 100644 --- a/StackApps.java +++ b/StackApps.java @@ -3,31 +3,62 @@ import java.util.Scanner; -public class StackApps -{ +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 - - // TODO: complete this method - - return stackBinary.toString(); // return a string representation of the stack + 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 - - // TODO: complete this method - + 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 - } + } }