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

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. // The StackApps class that implements two Stack applications
  2. // Your name here
  3. import java.util.Scanner;
  4. public class StackApps
  5. {
  6. // convert a decimal number into a binary number and save it in a stack
  7. // Do not create any arrays! Do not use any Java libraries to do the convertion.
  8. // Doing so will result in points deduction.
  9. public String decToBin(int numDec)
  10. {
  11. CharStack stackBinary = new CharStack(64); // stack used to store the result binary number
  12. while (numDec > 0) {
  13. if (numDec % 2 == 0)
  14. stackBinary.push('0');
  15. else
  16. stackBinary.push('1');
  17. numDec /= 2;
  18. }
  19. return stackBinary.toString(); // return a string representation of the stack
  20. }
  21. // compute the sum of the two big intergers and save the result in a stack
  22. // Do not create any arrays! Do not use any Java libraries to do the calculation.
  23. // Doing so will result in points deduction.
  24. public String addBigIntegers(String num1, String num2)
  25. {
  26. CharStack stackNum1 = new CharStack(64); // stack used to store number 1
  27. CharStack stackNum2 = new CharStack(64); // stack used to store number 2
  28. CharStack stackResult = new CharStack(64); // stack used to store the result of the addition
  29. CharStack remaining;
  30. for (int i = 0; i < num1.length(); i += 1)
  31. stackNum1.push(num1.charAt(i));
  32. for (int i = 0; i < num2.length(); i += 1)
  33. stackNum2.push(num2.charAt(i));
  34. int carry = 0;
  35. int a;
  36. int b;
  37. int result;
  38. while (!(stackNum1.isEmpty() || stackNum2.isEmpty())) {
  39. a = (int) (stackNum1.pop() - '0');
  40. b = (int) (stackNum2.pop() - '0');
  41. result = (a+b+carry);
  42. carry = result/10;
  43. stackResult.push((char)((result%10) + '0'));
  44. }
  45. if (stackNum1.isEmpty())
  46. remaining = stackNum2;
  47. else
  48. remaining = stackNum1;
  49. while (!(remaining.isEmpty())) {
  50. a = (int) (remaining.pop() - '0');
  51. result = (a+carry);
  52. carry = result/10;
  53. stackResult.push((char)((result%10) + '0'));
  54. }
  55. if (carry > 0)
  56. stackResult.push((char)(carry + '0'));
  57. return stackResult.toString(); // return a string representation of the stack
  58. }
  59. }