Advertisement
Guest User

Untitled

a guest
Dec 18th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. // you can write to stdout for debugging purposes, e.g.
  2. // console.log('this is a debug message');
  3.  
  4. console.log(solution('13000000000 DUP 4 POP 5 DUP + DUP + +'));
  5. console.log(Number.MAX_VALUE);
  6. function solution(S) {
  7. //split S
  8. var res = S.split(' ');
  9. var stack = []; // stack is now []
  10. /*stack.push(2); // stack is now [2]
  11. stack.push(5); // stack is now [2, 5]
  12. var i = stack.pop(); // stack is now [2]*/
  13. for (var i = 0; i < res.length; i++) {
  14. console.log(stack.toString());
  15. switch (res[i]) {
  16. case 'POP':
  17. if(stack.length==0){
  18. return -1;
  19. }else{
  20. stack.pop();
  21. }
  22. break;
  23. case 'DUP':
  24. if(stack.length==0){
  25. return -1;
  26. }else{
  27. // duplicate last value
  28. stack.push(stack[stack.length-1]);
  29. }
  30. break;
  31. case '-':
  32. if(stack.length<=1 || (stack[stack.length-2]>stack[stack.length-1])){
  33. return -1;
  34. }else{
  35. var firstLastValue = stack.pop();
  36. var secondLastValue = stack.pop();
  37. stack.push(firstLastValue-secondLastValue);
  38. }
  39. break;
  40. case '+':
  41. if(stack.length<=1){
  42. return -1;
  43. }else{
  44. var firstLastValue = stack.pop();
  45. var secondLastValue = stack.pop();
  46. stack.push(firstLastValue+secondLastValue);
  47. }
  48. break;
  49. default:
  50. // there is no 'long' in javascript.
  51. stack.push(parseInt(res[i]));
  52. break;
  53. }
  54. }
  55. return stack.pop();
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement