思路

  • 一个好用的函数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #include <stdlib.h>

    int atoi(const char *str);


    const char *numStr = "1234";
    int num = atoi(numStr); // 将字符串转换为整数
    printf("转换后的整数是: %d\n", num); // 输出: 转换后的整数是: 1234

  • 自己写的笨比算法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    int evalRPN(char** tokens, int tokensSize) {
    int stack[tokensSize];
    int top = -1;

    for (int i = 0; i < tokensSize; i++) {
    // 判断是否是加号
    if (strcmp(tokens[i], "+") == 0) {
    int b = stack[top--];
    int a = stack[top--];
    stack[++top] = a + b;
    }
    // 判断是否是减号
    else if (strcmp(tokens[i], "-") == 0) {
    int b = stack[top--];
    int a = stack[top--];
    stack[++top] = a - b;
    }
    // 判断是否是乘号
    else if (strcmp(tokens[i], "*") == 0) {
    int b = stack[top--];
    int a = stack[top--];
    stack[++top] = a * b;
    }
    // 判断是否是除号
    else if (strcmp(tokens[i], "/") == 0) {
    int b = stack[top--];
    int a = stack[top--];
    stack[++top] = a / b;
    }
    // 如果是数字,则将其转换为整数并压入栈
    else {
    stack[++top] = atoi(tokens[i]);
    }
    }
    return stack[top];
    }

    image-20241105160933900