题解 | #大数加法#
大数加法
https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 计算两个数之和 * @param s string字符串 表示第一个整数 * @param t string字符串 表示第二个整数 * @return string字符串 */ #include <stdlib.h> #include <string.h> char* solve(char* s, char* t ) { // write code here int sLen = strlen(s); int tLen = strlen(t); int retLen = 0; if(0 == sLen){ return t; } if(0 == tLen){ return s; } if(sLen >= tLen){ retLen = sLen + 2; }else{ retLen = tLen + 2; } //char *result = (char*)malloc(retLen); char *result = (char*)calloc(retLen, sizeof(char)); int sPos = sLen - 1; int tPos = tLen - 1; int retPos = 0; int jinWei = 0; int sum = 0; int i, j; while(sPos >= 0 || tPos >= 0 || jinWei > 0){ int sInt = sPos >= 0 ? s[sPos--] - '0' : 0; int tInt = tPos >= 0 ? t[tPos--] - '0' : 0; sum = sInt + tInt + jinWei; if(sum >= 10){ result[retPos++] = sum % 10 + '0'; jinWei = 1; }else{ result[retPos++] = sum + '0'; jinWei = 0; } } //result[retPos] = '\0'; for(int i = 0, j = retPos - 1; i<j; i++, j--){ char t = result[i]; result[i] = result[j]; result[j] = t; } return result; }