4 条题解
-
3
写在前面 这道题不难,我用这道题学习了一下字符串拼接和字符串加法进位,其实还想学习一下atoi函数和stoi函数,后来也没用。我这道题有很多细节在一开始并没有注意,导致出现了很多问题,想把代码分享出来,希望之后的同学注意细节。
#include <math.h> #include <string.h> #include <iostream> int main() { int T = 0; std::cin >> T; for (int i = 0; i < T; i++) { int jinWei = 0; // 这里只可能是0或1其他的情况都是错的 std::string count1; std::string count2; std::string result; std::cin >> count1 >> count2; std::string result1 = count1;//16 17两行是用来保存输入的字符串不被前导零覆盖,输出使用 std::string result2 = count2; int length1 = std::max(count1.length(), count2.length()); // 22 到 32 部分是用来比较两字符串长度并且变为等长 int lenMin = count1.length(); int lenMax = count2.length(); std::string m = ""; for (int j = 0; j < std::abs(lenMax - lenMin); j++) { m = m + "0"; } if (count1.length() > count2.length()) { count2 = m + count2; } else if (count1.length() < count2.length()) { count1 = m + count1; } for (int j = length1 - 1; j >= 0; j--) { int tempstr; int temp1 = 0; int temp2 = 0; temp1 = count1[j] - '0'; temp2 = count2[j] - '0'; int sum = temp1 + temp2 + jinWei; if (sum >= 10) { jinWei = 1; } else { jinWei = 0; } int yuShu = (sum) % 10; tempstr = yuShu; result = std::to_string(tempstr) + result; } std::cout << "Case " << i + 1 << ":" << std::endl; std::cout << result1 << " + " << result2 << " = "; if (jinWei == 1) { std::cout << "1"; } std::cout << result << std::endl; } }
信息
- ID
- 165
- 时间
- 3000ms
- 内存
- 128MiB
- 难度
- 8
- 标签
- (无)
- 递交数
- 1474
- 已通过
- 177
- 上传者