【2024华为OD-E卷-100分-火星文计算】(题目+思路+Java&C++&Python解析)

题目描述

给定一个火星文字符串,每个火星文字符代表一个0到9之间的数字。我们需要实现一个火星文计算器,支持加法、减法、乘法和除法四种基本运算。火星文字符和数字的对应关系是预先给定的,通过一个映射表提供。

输入

  1. 第一行是一个整数 n,表示火星文字符和数字的映射关系数量。
  2. 接下来的 n 行,每行包含一个火星文字符和一个对应的数字,用空格分隔。
  3. 最后一行是一个火星文表达式,包含火星文字符和四种运算符(+,-,*,/)。

输出

输出火星文表达式的计算结果。

示例

输入

5
a 1
b 2
c 3
d 4
e 5
a+b*c-d/e

输出

5

思路

  1. 解析映射表:首先,将火星文字符和数字的映射关系存储在一个哈希表中,以便快速查找。
  2. 解析表达式:遍历火星文表达式,识别出每个火星文字符和运算符,并根据映射表将火星文字符转换为对应的数字。
  3. 计算表达式:使用栈来处理运算符和数字,根据运算符的优先级进行计算。
  4. 输出结果:最终得到计算结果并输出。

Java编码解析

import java.util.*;

public class MarsCalculator {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        int n = scanner.nextInt();
        Map<Character, Integer> map = new HashMap<>();
        
        for (int i = 0; i < n; i++) {
            char character = scanner.next().charAt(0);
            int number = scanner.nextInt();
            map.put(character, number);
        }
        
        String expression = scanner.next();
        scanner.close();
        
        int result = evaluateExpression(expression, map);
        System.out.println(result);
    }
    
    private static int evaluateExpression(String expression, Map<Character, Integer> map) {
        Deque<Integer> numbers = new ArrayDeque<>();
        Deque<Character> operators = new ArrayDeque<>();
        
        for (int i = 0; i < expression.length(); i++) {
            char ch = expression.charAt(i);
            
            if (Character.isLetter(ch)) {
                numbers.push(map.get(ch));
            } else if (isOperator(ch)) {
                while (!operators.isEmpty() && precedence(operators.peek()) >= precedence(ch)) {
                    char op = operators.pop();
                    int b = numbers.pop();
                    int a = numbers.pop();
                    numbers.push(applyOperator(a, b, op));
                }
                operators.push(ch);
            }
        }
        
        while (!operators.isEmpty()) {
            char op = operators.pop();
            int b = numbers.pop();
            int a = numbers.pop();
            numbers.push(applyOperator(a, b, op));
        }
        
        return numbers.pop();
    }
    
    private static boolean isOperator(char ch) {
        return ch == '+' || ch == '-' || ch == '*' || ch == '/';
    }
    
    private static int precedence(char op) {
        if (op == '+' || op == '-') {
            return 1;
        } else if (op == '*' || op == '/') {
            return 2;
        }
        return 0;
    }
    
    private static int applyOperator(int a, int b, char op) {
        switch (op) {
            case '+': return a + b;
            case '-': return a - b;
            case '*': return a * b;
            case '/':
                if (b == 0) throw new ArithmeticException("Division by zero");
                return a / b;
            default: return 0;
        }
    }
}

C++编码解析

#include <iostream>
#include <unordered_map>
#include <stack>
#include <string>
#include <cctype>

using namespace std;

int precedence(char op) {
    if (op == '+' || op == '-') return 1;
    if (op == '*' || op == '/') return 2;
    return 0;
}

int applyOperator(int a, int b, char op) {
    switch (op) {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/':
            if (b == 0) throw runtime_error("Division by zero");
            return a / b;
        default: return 0;
    }
}

int evaluateExpression(const string& expression, const unordered_map<char, int>& map) {
    stack<int> numbers;
    stack<char> operators;
    
    for (char ch : expression) {
        if (isalpha(ch)) {
            numbers.push(map.at(tolower(ch)));
        } else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
            while (!operators.empty() && precedence(operators.top()) >= precedence(ch)) {
                char op = operators.top(); operators.pop();
                int b = numbers.top(); numbers.pop();
                int a = numbers.top(); numbers.pop();
                numbers.push(applyOperator(a, b, op));
            }
            operators.push(ch);
        }
    }
    
    while (!operators.empty()) {
        char op = operators.top(); operators.pop();
        int b = numbers.top(); numbers.pop();
        int a = numbers.top(); numbers.pop();
        numbers.push(applyOperator(a, b, op));
    }
    
    return numbers.top();
}

int main() {
    int n;
    cin >> n;
    
    unordered_map<char, int> map;
    for (int i = 0; i < n; ++i) {
        char ch;
        int num;
        cin >> ch >> num;
        map[tolower(ch)] = num;
    }
    
    string expression;
    cin >> expression;
    
    try {
        int result = evaluateExpression(expression, map);
        cout << result << endl;
    } catch (const exception& e) {
        cout << e.what() << endl;
    }
    
    return 0;
}

Python编码解析

def precedence(op):
    if op in ('+', '-'):
        return 1
    if op in ('*', '/'):
        return 2
    return 0

def apply_operator(a, b, op):
    if op == '+': return a + b
    if op == '-': return a - b
    if op == '*': return a * b
    if op == '/':
        if b == 0: raise ZeroDivisionError("Division by zero")
        return a // b  # Integer division
    return 0

def evaluate_expression(expression, map):
    numbers = []
    operators = []
    
    for ch in expression:
        if ch.isalpha():
            numbers.append(map[ch.lower()])
        elif ch in ('+', '-', '*', '/'):
            while operators and precedence(operators[-1]) >= precedence(ch):
                op = operators.pop()
                b = numbers.pop()
                a = numbers.pop()
                numbers.append(apply_operator(a, b, op))
            operators.append(ch)
    
    while operators:
        op = operators.pop()
        b = numbers.pop()
        a = numbers.pop()
        numbers.append(apply_operator(a, b, op))
    
    return numbers[0]

if __name__ == "__main__":
    n = int(input().strip())
    char_to_num = {}
    for _ in range(n):
        char, num = input().strip().split()
        char_to_num[char.lower()] = int(num)
    
    expression = input().strip()
    
    try:
        result = evaluate_expression(expression, char_to_num)
        print(result)
    except ZeroDivisionError as e:
        print(e)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执着的小火车

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值