#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> void reverse_str(char *pBegin, char *pEnd){ while(pBegin < pEnd){ char t = *pBegin; *pBegin = *pEnd; *pEnd = t; ++pBegin; --pEnd; } } bool add(const char *pA, const char *pB, char *pSum, int maxSumLen){ if(pA == NULL || pB == NULL || pSum == NULL || maxSumLen <= 0){ return false; } int lenA = strlen(pA); int lenB = strlen(pB); int k = 0; pSum[k] = 0; for(int i = lenA - 1, j = lenB - 1; (k <= maxSumLen - 2 && (i >= 0 || j >= 0)); i--, j--, k++){ int a = i >= 0 ? pA[i] - '0' : 0; int b = j >= 0 ? pB[j] - '0' : 0; pSum[k] += a + b; pSum[k + 1] = pSum[k] >= 10 ? pSum[k] / 10 : 0; pSum[k] = pSum[k] % 10 + '0'; } pSum[k] = ' '; reverse_str(pSum, pSum + k - 1); return true; } int main(){ char strA[] = "123499999"; char strB[] = "223999999"; char strSum[10]; add(strA, strB, strSum, 10); printf("strA:%s, strB:%s, strSum:%s ", strA, strB, strSum); printf("result:%d ", atoi(strSum) == (atoi(strA) + atoi(strB))%1000000000); return 0; }