JavaScript Arithmetic: Subtraction

Source: Internet
Author: User
Tags arithmetic end expression pow return

These days also in the study of JavaScript, a few days ago, the teacher gave an article about parsing arithmetic expression and algorithm, said arithmetic very often let me take a good look, and then to write code to see the final results.

First I looked at the code for two representations about arithmetic or logical formulas: infix notation and reverse Polish notation, as well as learning 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's code, his analysis to understand, and then add some code. In the process of consolidating learning about the stack of knowledge as well as the stack (LIFO) and queue (FIFO) method.

The following code is the code that you think is more complete:

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

function Isoperator (value) {
var operatorstring = "+-*/()";
return Operatorstring.indexof (value) > 1
}

function Getprioraty (value) {
Switch (value) {
Case ' + ':
Case '-':
return 1;
Case ' * ':
Case '/':
return 2;
Default
return 0;
}
}

Judge the priority of subtraction
function Prioraty (O1, O2) {
Return Getprioraty (O1) <= getprioraty (O2);
}

Define input, output stacks, and output queues, which are added to the end of the input stack one at a time, followed by symbols and numbers, and special handling when "(and") are found:

function DAL2RPN (exp) {
Input stack
var inputstack = [];
Output stacks
var outputstack = [];
Output queues
var outputqueue = [];

for (var i = 0, len = exp.length i < len; i++) {
var cur = exp[i];
if (cur!= ') {
Inputstack.push (cur); +-*/() number, added to the end individually
}
}

Working with characters and numbers
while (Inputstack.length > 0) {

Shift top to get an item to remove, Unshift top push
cur = inputstack.shift ();

If the symbol--> +-*/()
if (Isoperator (cur)) {
if (cur = = ' (') {
Push pushes from the tail into a
Outputstack.push (cur);
' Else if (cur = = ') ') {
The pop gets an item from the tail and then moves out
var po = outputstack.pop ();
while (PO!= ' && outputstack.length > 0) {
Outputqueue.push (PO);
PO = Outputstack.pop ();
}
if (PO!= ' (') {
Throw "Error: no match";
}
} else {//symbol, processing +-*/
while (Prioraty (cur, outputstack[outputstack.length-1])
&& outputstack.length > 0) {
Outputqueue.push (Outputstack.pop ());
}
Outputstack.push (cur);
}
If else {//is a number, push the number
Outputqueue.push (new number (cur));
}
}

if (Outputstack.length > 0) {
if (outputstack[outputstack.length-1] = = ') '
Outputstack[outputstack.length-1] = = ' (') {
Throw "Error: no match";
}
while (Outputstack.length > 0) {
Outputqueue.push (Outputstack.pop ());
}
}
Return EVALRPN (Outputqueue);
}

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

function Evalrpn (queue) {
var outputstack = [];
while (Queue.length > 0) {
var cur = queue.shift ();

if (!isoperator (cur)) {
Outputstack.push (cur);
} else {
If the output stack length is less than 2
if (Outputstack.length < 2) {
Throw "Invalid stack length";
}
var second = Outputstack.pop ();
var-i = Outputstack.pop ();

Outputstack.push (GetResult (second, cur));
}
}

if (outputstack.length!= 1) {
Throw "Incorrect operation";
} else {
return outputstack[0];
}
}

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

function GetResult (second, operator) {
var result = 0;
Switch (operator) {
Case ' + ':
result = second;
Break
Case '-':
result = First-second;
Break
Case ' * ':
result = second;
Break
Case '/':
result = First/second;
Break
Default
return 0;
}

When a floating-point number is more than two digits, only the two-digit decimal point is preserved
function formatfloat (f, digit) {
Pow (10,n) is 10 n-th Square
var m = math.pow (digit);
return parseint (f * m, ten)/m;
}
Return (Formatfloat (result, 2));
}

Enter the expression to be evaluated, and the result (0.6) is calculated:

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



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.