【C language】—— Realize simple four arithmetic operations

Realize simple four arithmetic expressions

foreword

When we use a calculator to perform simple addition, subtraction, multiplication, and division, we need to pay attention to many issues. The most important thing is that the arithmetic priority of multiplication and division is different from that of addition and subtraction. What should we do if we enter a series of continuous inputs? To answer the question correctly?

problem solving ideas

When faced with this problem, the first method I thought of was to store the data and operators in two arrays respectively, then traverse the operator array, filter out the multiplication and division, and finally perform addition and subtraction operation.

The above method can actually solve this problem, but the time complexity is too high, and it feels a bit violent. This problem can be solved by using the stack method. The special processing method of the stack is first-in-last-out, so we can think of using two The stack uses its special processing method to realize simple four arithmetic operations.

The first stack is used to store data. All the numbers in the string you input are stored in this stack for subsequent use. The other stack is used to store symbols. You need to consider how to achieve multiplication and division before addition and subtraction At this time, we can assign different priorities to its special symbols, and use numbers to represent their priorities. The larger the higher, the symbols in the string we input are pressed one by one by comparison. In the stack, if the priority is greater than or equal to the symbol on the top of the stack, then push it into the stack. If the priority is less than the symbol on the top of the stack, take two elements in the number stack and the top of the symbol stack to perform operations, and store the result in the stack . The only value in the final data stack is the final score.

Suppose we want to calculate the formula 1×2+3×4:
Let’s simulate this step:
insert image description here
Then the second step:
insert image description here

Step 3:
insert image description here
The last step is to complete the addition operation.

The whole code is as follows:

#include <stdio.h>
#include <string.h>
int Calculation(int a, char c, int b);
void ScanfData();
int Compare(char ch);
int main() {
    
    
	ScanfData();
	return 0;
}

int Calculation(int a, char c, int b) {
    
    
	if (c == '+') {
    
    
		return a + b;
	} else if (c == '-') {
    
    
		return a - b;
	} else if (c == '*') {
    
    
		return a * b;
	} else if (c == '/') {
    
    
		return a / b;
	} else {
    
    
		return -1;
	}
}
void ScanfData() {
    
    
	int numStack[100] = {
    
    0};
	int numTop = -1;	
	char symStack[100] = {
    
    '='};
	int symTop = 0;	
	char str[100];
	int flag = -1;
	scanf("%s", str);
	int x = 0;
	int length = (int)strlen(str); 
	int i = 0;
	while (i < length) {
    
    
        if (str[i] >= '0' && str[i] <= '9') {
    
    
            x = x * 10 + (str[i++] - '0');
            flag = 1;
        } else {
    
    
            if (flag == 1) {
    
    
                numStack[++numTop] = x;
                x = 0;
                flag = -1;
            }
            if (Compare(symStack[symTop]) < Compare(str[i])) {
    
    
                symStack[++symTop] = str[i++];
            } else {
    
    
                int b = numStack[numTop--];
                int a = numStack[numTop--];
                numStack[++numTop] = Calculation(a, symStack[symTop], b);
                symTop--;
                if (str[i] == '=' && symTop == 0) {
    
    
                    break;
                }
            }
        }
    }
    printf("%d", numStack[numTop]);
}
int Compare(char c) {
    
    
	if (c == '=') {
    
    
		return 0;
	} else if (c == '+' || c == '-') {
    
    
		return 1;
	} else if (c == '*' || c == '/') {
    
    
		return 2;
	} else {
    
    
		printf("error");
		return -1;
	}
}

Stack and queue simple practice questions:

insert image description here

char* removeDuplicates(char* s) {
    
    
    int len = strlen(s);
    int i, j = 0;
    char *q = (char *)malloc(sizeof(char) * len);
    for (i = 0; i < len; i++) {
    
    
    	q[j] = s[i];
    	if (j > 0) {
    
    
    		if (q[j] == q[j - 1]) {
    
    
    			j = j - 2;
			}
		}
		j++;
	}
	q[j] = '\0';
	return q;
}

insert image description here

int countStudents(int* students, int studentsSize, int* sandwiches, int sandwichesSize){
    
    
    int stu0 = 0, stu1 = 0;
	int i;
	for (i = 0; i < studentsSize; i++) {
    
    
		if (students[i] == 0) {
    
    
			stu0++;
		} else {
    
    
			stu1++;
		}
	} 
	for (i = 0; i < sandwichesSize; i++) {
    
    
		if (sandwiches[i] == 0) {
    
    
			if (stu0 == 0) {
    
    
				return studentsSize - i;
			} else {
    
    
				stu0--;
			}
		} else {
    
    
			if (stu1 == 0) {
    
    
				return studentsSize - i;
			} else {
    
    
				stu1--;
			}
		}
	}
	return 0;
}

insert image description here

int timeRequiredToBuy(int* tickets, int ticketsSize, int k){
    
    
    int i = 0, count = 0;
    if (tickets[k] == 0) {
    
    
    	return 0;
	}
	while (i <= k) {
    
    
		for (int j = 0; j < ticketsSize; j++) {
    
    
			tickets[j]--;
			if (tickets[j] >= 0) {
    
    
				count++;
			}
			if (tickets[k] == 0) {
    
    
				return count;
			}
		}
	}
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_62386635/article/details/126940247