当前位置:网站首页>高精度减法
高精度减法
2022-08-10 22:46:00 【Ding Jiaxiong】
题目
给定两个正整数(不含前导 0),计算它们的差,计算结果可能为负数。
输入格式
共两行,每行包含一个整数。
输出格式
共一行,包含所求的差。
数据范围
1≤整数长度≤105
输入样例:
32
11
输出样例:
21
思路分析
题解
#include <iostream>
#include <vector>
using namespace std;
bool cmp(vector<int> &A, vector<int> &B)
{
if (A.size() != B.size()) return A.size() > B.size();
for (int i = A.size() - 1; i >= 0; i -- )
if (A[i] != B[i])
return A[i] > B[i];
return true;
}
vector<int> sub(vector<int> &A, vector<int> &B)
{
vector<int> C;
for (int i = 0, t = 0; i < A.size(); i ++ )
{
t = A[i] - t;
if (i < B.size()) t -= B[i];
C.push_back((t + 10) % 10);
if (t < 0) t = 1;
else t = 0;
}
while (C.size() > 1 && C.back() == 0) C.pop_back();
return C;
}
int main()
{
string a, b;
vector<int> A, B;
cin >> a >> b;
for (int i = a.size() - 1; i >= 0; i -- ) A.push_back(a[i] - '0');
for (int i = b.size() - 1; i >= 0; i -- ) B.push_back(b[i] - '0');
vector<int> C;
if (cmp(A, B)) C = sub(A, B);
else C = sub(B, A), cout << '-';
for (int i = C.size() - 1; i >= 0; i -- ) cout << C[i];
cout << endl;
return 0;
}
边栏推荐
猜你喜欢
koa框架(一)
"DevOps Night Talk" - Pilot - Introduction to CNCF Open Source DevOps Project DevStream - feat. PMC member Hu Tao
高学历毕业生,该学单片机还是plc?
MySQL学习笔记(1)——基础操作
BM7 链表中环的入口结点
How does the Weiluntong touch screen display the current value of abnormal data while alarming?
Merge k sorted linked lists
实例052:按位或
Pytorch面试题面经
这款可视化工具神器,更直观易用!太爱了
随机推荐
leetcode:357. 统计各位数字都不同的数字个数
DC-7靶场下载及渗透实战详细过程(DC靶场系列)
Research on multi-element N-k fault model of power system based on AC power flow (implemented by Matlab code) [Power System Fault]
MySQL: MySQL Cluster - Principle and Configuration of Master-Slave Replication
CFdiv2-Beautiful Mirrors-(期望)
【640. 求解方程】
file IO-buffer
Take you to build a wheel and customize a View that can be dragged and sucked at will
CIKM2022 | Sequence Recommendation Based on Bidirectional Transformers Contrastive Learning
二叉树 | 翻转二叉树 | leecode刷题笔记
BM13判断一个链表是否为回文结构
Apache Doris支持的数据类型详解
The Missing Semester of Your CS Education
实例051:按位与
MySQL之JDBC编程增删改查
【640. Solving Equations】
面试官: AMS在Android起到什么作用,简单的分析下Android的源码
开源一夏 | 盘点那些 Golang 标星超过 20 K 的优质项目
【秋招】【更新中ing】手撕代码系列
canvas