3 条题解
-
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; } }
-
0
可能有点写的不太好,有错误可指出 #include<stdio.h> #include<string.h> void jinwei(char *num1,char *num2,char*sum) { //为了方便进行进位加法,先将字符串进行反转 //反转之前先计算长度 int len1 = strlen(num1); int len2 = strlen(num2); //对数组num1进行反转 for(int i=0;i<len1/2;i++) { char temp = num1[i]; num1[i] = num1[len1-1-i]; num1[len1-i-1] = temp; } //对数组num2进行反转 for(int i=0;i<len2/2;i++) { char temp = num2[i]; num2[i] = num2[len2-i-1]; num2[len2-i-1] = temp; } //下面进行加法进位 //加法之前先算出和的数的大概位数 int maxlen = (len1 > len2)?len1:len2; int yushu = 0; for(int i=0;i<maxlen;i++) { int dight1 = (i<len1)?num1[i] - '0':0; int dight2 = (i<len2)?num2[i] - '0':0; int su = dight1 + dight2 + yushu; sum[i] = (su%10) + '0'; yushu = su/10; } if(yushu>0) { sum[maxlen] = yushu + '0'; maxlen++; } //把结果字符串进行反转 for(int i=0;i<maxlen/2;i++) { char temp = sum[i]; sum[i] = sum[maxlen-i-1]; sum[maxlen-i-1] = temp; } sum[maxlen] = '\0'; } int main() { int n; scanf("%d",&n); int x = 1; while(n--) { char a[1000] = {0}; char b[1000] = {0}; char result[1000] = {0}; scanf("%s",a); scanf("%s",b); char c[1000] = {0}; char d[1000] = {0}; int len1 = strlen(a); int len2 = strlen(b); strcpy(c,a); strcpy(d,b); c[len1] = '\0'; d[len2] = '\0'; jinwei(a,b,result); printf("Case %d:\n",x); x++; printf("%s + %s = %s\n",c,d,result); } }
- 1
信息
- ID
- 165
- 时间
- 3000ms
- 内存
- 128MiB
- 难度
- 8
- 标签
- (无)
- 递交数
- 1453
- 已通过
- 173
- 上传者