hduoj1002 A + B Problem II (大數相加 字串模擬)
hduoj1002 A + B Problem II
Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
Output
For each test case, you should output two lines. The first line is “Case #:”, # means the number of the test case. The second line is the an equation “A + B = Sum”, Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
Sample Input
2
1 2
112233445566778899 998877665544332211
Sample Output
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
思路:字串模擬 |
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
string add_BigInt(string a,string b){
int x = a.size(), y = b.size();
x > y ? b.insert(b.begin(), x - y, '0'):a.insert(a.begin(),y - x,'0');
int carry = 0;
int n = a.size();
string res = "";
for(int i = n - 1; i >= 0; i--){
int cur = (a[i] - '0') + (b[i] - '0') + carry;
res += '0' + cur % 10;
carry = cur / 10;
}
if(carry) res += "1";
while(res.back() == '0' && res.size() > 1) res.pop_back();
reverse(res.begin(),res.end());
return res;
}
int main(){
int T; cin >> T;
for (int i = 1; i <= T; i++) {
string a,b;
cin >> a >> b;
cout << "Case " << i << ":" << endl;
cout << a << " + " << b << " = " << add_BigInt(a,b) << endl;
if (i != T) cout << endl;
}
return 0;
}
相關文章
- A + B Problem II hd 1002
- HDU 1002 A + B Problem II
- LeetCode-2. 兩數相加(連結串列+大數加法模擬)LeetCode
- 454_四數相加Ii
- PAT-B 1017 A除以B【模擬 大數除法】
- PAT-B 1024 科學計數法【模擬+字串】字串
- PHP字串數字相加PHP字串
- The 2024 ICPC Asia EC Regionals Online Contest (II) - Problem B. Mountain BookingAI
- 模擬賽38 B. T形覆蓋 大模擬
- C++每日一練26-四數相加 IIC++
- Add Strings 字串相加字串
- 我倒在了美團面試演算法題:字串大數相加面試演算法字串
- 【一天一大 lee】四數相加 II (難度:中等) - Day20201127
- PAT-B 1084 外觀數列 【模擬】
- LeetCode-415-字串相加LeetCode字串
- PAT-B 1019 數字黑洞【陣列+模擬】陣列
- P1865 A % B Problem
- PAT-B 1012 數字分類【簡單模擬】
- PAT-B 1079 延遲的迴文數【字串+大數加法】字串
- Facebook 面試題 | 字串相加面試題字串
- 垂直柱狀圖(模擬+字串)字串
- Problem 4:替換空格(字串)字串
- [Algorithm] 1. A+B ProblemGo
- QOJ6836 A Plus B Problem
- 漫畫:如何實現大整數相加?
- 大數模擬 加減乘除 判斷大數是否為素數 板子
- Problem L: 第二大的數
- PAT-B 1027 列印沙漏 【模擬】
- 1014 CW 模擬賽 B.旅行
- 字串的調整II字串
- PAT-B 1048 數字加密【字串】加密字串
- Day 7| 454.四數相加II 、383. 贖金信 、15. 三數之和 、18. 四數之和
- 兩數相加Ⅰ和Ⅱ
- Leetcode兩數相加LeetCode
- LeetCode——兩數相加LeetCode
- PAT-B 1058 選擇題 【模擬】
- PAT-B 1061 判斷題【模擬】
- PAT-B 1067 試密碼【模擬】密碼