题解 | #NC1-大数加法#

大数加法

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

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 * 计算两个数之和
 * @param s string字符串 表示第一个整数
 * @param t string字符串 表示第二个整数
 * @return string字符串
 */
char* solve(char* s, char* t ) {
    // write code here
    int sLen = strlen(s);
    int tLen = strlen(t);
    int resultLen;
    
    if(sLen == 0)
        return t;
    if(tLen == 0)
        return s;
    //2个数字相加,和的位数最多为较长数字位数+1,因为是字符串,预留一个'\0'的位置,所有+2
    if(sLen > tLen)
        resultLen = sLen+2;
    else
        resultLen = tLen+2;

    //char *result = (char *)malloc(sizeof(char)*resultLen);
    char *result = (char *)calloc(resultLen, sizeof(char));
    int sPos = sLen-1;//求和从最后一位开始
    int tPos = tLen-1;
    int resPos = 0;//记录和的字符串当前位置
    int carry = 0;//进位
    int sum = 0;//求和
    int i, j;//翻转字符串
    
    while(sPos >= 0 || tPos >=0 || carry >0)
    {
        //从后往前,取每位的数字,若较长数字位有效,但较短数字位无效,则较短数字位返回0
        int n1 = sPos >= 0 ? s[sPos--]-'0' : 0;
        int n2 = tPos >= 0 ? t[tPos--]-'0' : 0;
        sum = n1 + n2 + carry;
        if(sum >= 10)
        {
            carry = 1;
            result[resPos++] = sum%10+'0';
        }
        else
        {
            carry = 0;
            result[resPos++] = sum+'0';
        }
    }
    
    //s=1,t=99时,result=001,需原地翻转字符串为100
    for(i = 0, j = resPos-1; i < j; i++, j--)
    {
        char tmp = result[i];
        result[i] = result[j];
        result[j] = tmp;
        
    }
        
    return result;
}

全部评论

相关推荐

01-30 09:45
燕山大学 Java
喵_coding:这种直接跑就完事了 哪有毕业了才签合同 任何offer和三方都没有的
点赞 评论 收藏
分享
合适才能收到offe...:招聘上写这些态度傲慢的就别继续招呼了,你会发现hr和面试官挺神的,本来求职艰难就可能影响一些心态了,你去这种公司面试的话,整个心态会炸的。
点赞 评论 收藏
分享
评论
12
2
分享

创作者周榜

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