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;
}
相關文章
- 454_四數相加Ii
- LeetCode-2. 兩數相加(連結串列+大數加法模擬)LeetCode
- PHP字串數字相加PHP字串
- PAT-B 1024 科學計數法【模擬+字串】字串
- 我倒在了美團面試演算法題:字串大數相加面試演算法字串
- C++每日一練26-四數相加 IIC++
- (陣列)大數相乘,相加陣列
- Facebook 面試題 | 字串相加面試題字串
- 山科 STUST OJ Problem B: 編寫函式:String to Double (II) (Append Code)函式APP
- 垂直柱狀圖(模擬+字串)字串
- PAT-B 1019 數字黑洞【陣列+模擬】陣列
- 漫畫:如何實現大整數相加?
- Add Strings 字串相加字串
- 二進位制字串相加字串
- The 2024 ICPC Asia EC Regionals Online Contest (II) - Problem B. Mountain BookingAI
- [Algorithm] 1. A+B ProblemGo
- LintCode-A+B Problem
- QOJ6836 A Plus B Problem
- P1865 A % B Problem
- YT15-HDU-字串的模擬字串
- elixir模擬ruby快速複製字串字串
- PAT-B 1079 延遲的迴文數【字串+大數加法】字串
- 資料庫中分組字串相加資料庫字串
- Problem 4:替換空格(字串)字串
- Codeforces Round #362 (Div. 2) B 模擬
- Day 7| 454.四數相加II 、383. 贖金信 、15. 三數之和 、18. 四數之和
- LeetCode-415-字串相加LeetCode字串
- 字串的調整II字串
- 模擬實現字串函式strlen , strcpy ,strcmp字串函式
- hihocoder 1261 String Problem II (Trie樹)
- PAT-B 1048 數字加密【字串】加密字串
- POJ-1503 Integer Inquiry-多個大數相加UI
- 2. 兩數相加
- 利用MySQL日誌模擬恢復資料變化軌跡IIMySql
- PAT-B 1067 試密碼【模擬】密碼
- Codeforces Round #323 (Div. 2) B 模擬
- 1014 CW 模擬賽 B.旅行
- 人工智慧大腦模擬人工智慧