• 大数加法


    #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;
    }
    

      

  • 相关阅读:
    Asp.Net 获取客户端真实IP方法总结
    C# 中英文符号互转(半角全角互转)
    执行git commit命令提示: “Please tell me who you are”的解决方案
    Tools
    VSC
    DevOps
    VSC
    DevOps
    DevOps
    K8S
  • 原文地址:https://www.cnblogs.com/moxiaopeng/p/4897551.html
Copyright © 2020-2023  润新知