题解 | #大数加法#

大数加法

https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475

C语言

char* solve(char* s, char* t ) {

    // write code here

    int iSCount = 0, iTCount = 0, iResCount = 0;    //声明s\t\res的长度变量

    char *pcTmp, *pcRes;

    // char pcRes[4];       //调试代码

    char iOvFlag = 0;       //进位标志

    pcTmp = s;              //计算得到s的长度

    while(*pcTmp++ != '\0'){

        iSCount++;

    }

    pcTmp = t;              //计算得到t的长度

    while(*pcTmp++ != '\0'){

        iTCount++;

    }

    iResCount = (iSCount > iTCount) ? iSCount+2 : iTCount+2;    //res长度取max(s,t)的长度+2。一个给结束符,一个预留给进位

    pcRes = (char *)malloc(sizeof(char)*(iResCount));      //返回结果动态申请内存

    pcRes[0]='0', pcRes[iResCount-1]='\0';                  //设置进位为'0',以及结束符

    iResCount -= 2;                                         //xxCount都用做索引,因此需要-1,

    iTCount -= 1;

    iSCount -= 1;

    while(iSCount >= 0 || iTCount >= 0){                

        if(iSCount >= 0 && iTCount >= 0){           //1、当s\t均不为空

            if(s[iSCount]-'0'+t[iTCount]-'0'+iOvFlag >= 10){    //s\t的右对齐的对应位相加再加上进位,溢出则-10后赋值并将进位标志置位

                pcRes[iResCount] = s[iSCount]-'0'+t[iTCount]-'0'+iOvFlag-10+'0';

                iOvFlag = 1;

            }else{                                              //不溢出则直接赋值,并将进位标志清空

                pcRes[iResCount] = s[iSCount]-'0'+t[iTCount]-'0'+iOvFlag+'0';

                iOvFlag = 0;

            }

        }else if(iSCount >= 0 && iTCount < 0){

            if(s[iSCount]-'0'+iOvFlag >= 10){

                pcRes[iResCount] = s[iSCount]-'0'+iOvFlag-10+'0';

                iOvFlag = 1;

            }else{

                pcRes[iResCount] = s[iSCount]-'0'+iOvFlag+'0';

                iOvFlag = 0;

            }

        }else if(iSCount < 0 && iTCount >= 0){

            if(t[iTCount]-'0'+iOvFlag >= 10){

                pcRes[iResCount] = t[iTCount]-'0'+iOvFlag-10+'0';

                iOvFlag = 1;

            }else{

                pcRes[iResCount] = t[iTCount]-'0'+iOvFlag+'0';

                iOvFlag = 0;

            }

        }    

        iTCount--;  //向左移位

        iSCount--;

        iResCount--;

    }

    if(iOvFlag==1){ //退出循环,此时判断进位标志,如果为1则将pcRes的iResCount(0位)置1。

        pcRes[iResCount] += iOvFlag;

    }

    if(pcRes[0] == '1') //根据是否有溢出位返回结果

        return pcRes;

    else

        return pcRes+1;

}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务