JavaScript Arithmetic: Subtraction

Source: Internet
Author: User
Tags pow

These days are also learning JavaScript, a few days ago the master gave an article on parsing arithmetic expressions and algorithms, said arithmetic is often used to let me take a good look, and then write code to see the final results.

First, I read the code. Two representations of arithmetic or logical formulas: infix notation and inverse Polish notation, as well as the actual conversion process of arithmetic (this definition is explained in detail in the original text).

Original: http://www.jb51.net/article/53537.htm

Then I read the author of the Code, my analysis to understand, and then add some code. This process reinforces learning about stacks and the stack (LIFO) and Queue (FIFO) methods.

The following code is a self-considered complete code:

First, the priority of the subtraction is judged, and the priority of * and/is higher than + and-:

1         functionIsoperator (value) {2             varoperatorstring = "+-*/()";3             returnOperatorstring.indexof (value) >-14         }5 6         functionGetprioraty (value) {7             Switch(value) {8                  Case+:9                  Case‘-‘:Ten                     return1; One                  Case‘*‘: A                  Case‘/‘: -                     return2; -                 default: the                     return0; -             } -         } -  +         //determine the priority of subtraction -         functionPrioraty (O1, O2) { +             returnGetprioraty (O1) <=Getprioraty (O2); A}

Defines inputs, output stacks, and output queues, which are added to the end of the input stack one by one, and then processed by symbols and numbers, when "(" and ")" are found for special handling:

1         functionDAL2RPN (exp) {2             //Input Stack3             varInputstack = [];4             //Output Stack5             varOutputstack = [];6             //Output Queue7             varOutputqueue = [];8 9              for(vari = 0, len = exp.length; i < Len; i++) {Ten                 varCur =Exp[i]; One                 if(Cur! = ") { AInputstack.push (cur);//+-*/() numbers, added one at a to the end -                 } -             } the  -             //handling characters and numbers -              while(Inputstack.length > 0) { -  +                 //shift top Gets a post-remove, unshift top push-in -Cur =Inputstack.shift (); +  A                 //if it is symbol--+-*/() at                 if(Isoperator (cur)) { -                     if(cur = = ' (') { -                         //Push pushes an item from the tail - Outputstack.push (cur); -}Else if(cur = = ') ') { -                         //pop Gets an item from the tail and then moves out in                         varPO =Outputstack.pop (); -                          while(Po! = ' (' && outputstack.length > 0) { to Outputqueue.push (PO); +PO =Outputstack.pop (); -                         } the                         if(Po! = ' (') { *                             Throw"Error: no match"; $                         }Panax Notoginseng}Else{//symbol, processing +-*/ -                          while(Prioraty (cur, outputstack[outputstack.length-1]) the&& outputstack.length > 0) { + Outputqueue.push (Outputstack.pop ()); A                         } the Outputstack.push (cur); +                     } -}Else{//when it's a number, push it into numbers. $Outputqueue.push (NewNumber (cur)); $                 } -             } -  the             if(Outputstack.length > 0) { -                 if(Outputstack[outputstack.length-1] = = ') 'Wuyi|| Outputstack[outputstack.length-1] = = ' (') { the                     Throw"Error: no match"; -                 } Wu                  while(Outputstack.length > 0) { - Outputqueue.push (Outputstack.pop ()); About                 } $             } -             returnEVALRPN (outputqueue); -}

Define the EVALRPN () function, which is calculated when the output stack is not less than 2 in length:

1         functionEVALRPN (queue) {2             varOutputstack = [];3              while(Queue.length > 0) {4                 varCur =Queue.shift ();5 6                 if(!isoperator (cur)) {7Outputstack.push (cur);8}Else {9                     //if the output stack length is less than 2Ten                     if(Outputstack.length < 2) { One                         Throw"Invalid stack Length"; A                     } -                     varSecond =Outputstack.pop (); -                     varFirst =Outputstack.pop (); the  - Outputstack.push (GetResult (first, second, cur)); -                 } -             } +  -             if(Outputstack.length! = 1) { +                 Throw"Incorrect operation"; A}Else { at                 returnOutputstack[0]; -             } -}

After the subtraction calculation, the values are manipulated and only two decimal points are retained when the number of decimal places for the floating-point numbers exceeds two bits:

1         functionGetResult (first, second, operator) {2             varresult = 0;3             Switch(operator) {4                  Case+:5result = First +second;6                      Break;7                  Case‘-‘:8result = First-second;9                      Break;Ten                  Case‘*‘: Oneresult = First *second; A                      Break; -                  Case‘/‘: -result = First/second; the                      Break; -                 default: -                     return0; -             } +  -             //when the number of floating-point numbers exceeds two digits, only two decimal places are reserved +             functionformatfloat (f, digit) { A                 //Pow (10,n) is 10 of the n-th square at                 varm = Math.pow (10, digit); -                 returnparseint (f * m, 10)/m; -             } -             return(Formatfloat (Result, 2)); -}

Enter the expression that you want to evaluate, and the result (result-0.6):

1         var result=dal2rpn (' (1 + 2) * ((3-4)/5) '); 2         Console.log (result);   // Output Results

JavaScript Arithmetic: Subtraction

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.