1018: A+B again

本文介绍了一种使用栈来处理大数加法的方法。针对传统32位整数处理大数的局限性,该算法通过字符串输入表示任意大小的整数,并确保计算正确性。文章详细展示了算法流程及其实现细节。

 

1018: A+B again

 

  • 题目描述:

谷学长有一个非常简单的问题给你,给你两个整数A和B,你的任务是计算A+B。

  • 输入:

输入的第一行包含一个整数T(T<=20)表示测试实例的个数,然后2*T行,分别表示A和B两个正整数。注意整数非常大,那意味着你不能用32位整数来处理。你可以确定的是整数的长度不超过1000。

  • 输出:

对于每一个样例,你应该输出两行,第一行是"Case #:",#表示第几个样例,第二行是一个等式"A+B=Sum",Sum表示A+B的结果。注意等式中有空格。

  • 样例输入

2
1
2
112233445566778899
998877665544332211
  • 样例输出

Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
#include<iostream>
#include <stack>
#include <stdlib.h>
#include <stack>
#include <cstring>
using namespace std;

int main()
{
    stack <int> n1;
    stack <int> n2;
    stack <int> sum;
    string str1,str2;
    char c1;
    char c2;
    int T;
    cin>>T;
    int carryTrans = 0;
    for (int i = 0; i < T; ++i) {
        cin >> str1;
        cin >> str2;
        if (str1.length() != str2.length()) {                        //如果长度不一致,首先进行等长处理
            if (str1.length() > str2.length()) {
                int temp1 = str1.length() - str2.length();
                for (int j = 0; j < temp1; ++j) {
                    char temp = '0';
                    int atoi(temp);
                    n2.push(temp - 48);
                }
            } else {
                int temp2 = str2.length() - str1.length();
                for (int j = 0; j < temp2; ++j) {
                    char temp = '0';
                    int atoi(temp);
                    n1.push(temp - 48);
                }
            }
        }
        for (int j1 = 0; j1 < str1.length(); ++j1) {
            char temp = str1[j1];
            int atoi(temp);
            n1.push(temp - 48);
        }
        for (int j2 = 0; j2 < str2.length(); ++j2) {
            char temp = str2[j2];
            int atoi(temp);
            n2.push(temp - 48);
        }
        int T2;
        if (str1.length() > str2.length()) {
            T2 = str1.length();
        } else {
            T2 = str2.length();
        }
        for (int k = 0; k < T2; k++) {
            int temp = n1.top() + n2.top() + carryTrans;
            if (temp >= 10) {
                temp = temp - 10;
                carryTrans = 1;
            }
            else{
                carryTrans = 0;
            }
            sum.push(temp);
            n1.pop();
            n2.pop();
        }
        if (carryTrans == 1){
            sum.push(1);
        }
        cout<<"Case "<<i+1<<":"<<endl;
        cout<<str1<<" + ";
        cout<<str2<<" = ";
        while (!sum.empty()) {
            cout << sum.top();
            sum.pop();
        }
        cout << endl;
    }
    return 0;
}

用了栈来储存数据,比起char数组可以按照数据的产犊来分配内存,而且之后的相加、输出都比较方便。

以下是一个使用Python实现的矩阵运算工具,支持用户输入矩阵、进行加法、乘法转置运算,并格式化输出结果。 ### 程序代码 ```python import numpy as np class MatrixTool: def __init__(self): self.matrix_a = None self.matrix_b = None def input_matrix(self, name="Matrix"): while True: try: rows = int(input(f"Enter the number of rows for {name}: ")) cols = int(input(f"Enter the number of columns for {name}: ")) if rows <= 0 or cols <= 0: print("Rows and columns must be greater than 0.") continue matrix = [] print(f"Enter the elements of {name} ({rows}x{cols}) row by row:") for i in range(rows): row = list(map(float, input(f"Row {i+1}: ").strip().split())) if len(row) != cols: raise ValueError("Incorrect number of elements in row.") matrix.append(row) return np.array(matrix) except ValueError as e: print(f"Invalid input: {e}. Please try again.") def add_matrices(self): if self.matrix_a.shape != self.matrix_b.shape: return "Error: Matrices must have the same dimensions for addition." return self.matrix_a + self.matrix_b def multiply_matrices(self): if self.matrix_a.shape[1] != self.matrix_b.shape[0]: return "Error: Number of columns in first matrix must equal number of rows in second matrix for multiplication." return np.dot(self.matrix_a, self.matrix_b) def transpose_matrix(self, matrix): return matrix.T def format_matrix(self, matrix, decimal_places=2): return np.round(matrix, decimals=decimal_places) def run(self): print("Welcome to the Matrix Operation Tool!") self.matrix_a = self.input_matrix("Matrix A") self.matrix_b = self.input_matrix("Matrix B") while True: print("\nChoose an operation:") print("1. Add matrices (A + B)") print("2. Multiply matrices (A × B)") print("3. Transpose Matrix A") print("4. Transpose Matrix B") print("5. Exit") choice = input("Enter your choice: ") if choice == '1': result = self.add_matrices() elif choice == '2': result = self.multiply_matrices() elif choice == '3': result = self.transpose_matrix(self.matrix_a) elif choice == '4': result = self.transpose_matrix(self.matrix_b) elif choice == '5': print("Exiting the program. Goodbye!") break else: print("Invalid choice. Please select a valid option.") continue if isinstance(result, str): print(result) else: formatted_result = self.format_matrix(result) print("Result:") print(formatted_result) if __name__ == "__main__": tool = MatrixTool() tool.run() ``` --- ### 代码解释 1. **类定义** 定义了一个名为`MatrixTool`的类,用于封装矩阵操作的功能。类中包含以下方法: - `input_matrix`: 用于从用户输入中获取矩阵。 - `add_matrices`: 实现矩阵加法。 - `multiply_matrices`: 实现矩阵乘法。 - `transpose_matrix`: 实现矩阵转置。 - `format_matrix`: 格式化矩阵输出,限制小数位数。 - `run`: 主程序入口,提供交互式菜单供用户选择操作。 2. **矩阵输入校验** 在`input_matrix`方法中,对用户输入的行数列数进行了合法性校验(必须大于0),并对每一行的元素数量进行检查以确保与列数一致。 3. **矩阵加法** 加法操作要求两个矩阵维度相同。如果维度不匹配,则返回错误提示。 4. **矩阵乘法** 乘法操作要求第一个矩阵的列数等于第二个矩阵的行数。如果不满足条件,则返回错误提示。 5. **矩阵转置** 使用NumPy库的`.T`属性实现矩阵转置。 6. **格式化输出** 使用`np.round`函数对矩阵中的元素进行四舍五入,限制输出的小数位数。 7. **主循环** 提供一个交互式菜单,允许用户选择不同的操作。程序会根据用户的选择执行相应的矩阵运算并输出结果。 --- ### 示例运行 #### 输入示例 ``` Welcome to the Matrix Operation Tool! Enter the number of rows for Matrix A: 2 Enter the number of columns for Matrix A: 2 Enter the elements of Matrix A (2x2) row by row: Row 1: 1 2 Row 2: 3 4 Enter the number of rows for Matrix B: 2 Enter the number of columns for Matrix B: 2 Enter the elements of Matrix B (2x2) row by row: Row 1: 5 6 Row 2: 7 8 Choose an operation: 1. Add matrices (A + B) 2. Multiply matrices (A × B) 3. Transpose Matrix A 4. Transpose Matrix B 5. Exit Enter your choice: 1 ``` #### 输出示例 ``` Result: [[ 6. 8.] [10. 12.]] ``` --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值