题解 | #大数加法#

大数加法

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

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 计算两个数之和
 * @param s string字符串 表示第一个整数
 * @param t string字符串 表示第二个整数
 * @return string字符串
 */
char* solve(char* s, char* t ) {
    // write code here
    int s1 = strlen(s) - 1;
    int t1 = strlen(t) - 1;
    printf("%d %d\n",s1,t1);
    //判断非空
    if (s1 == -1)
        return t;
    if (t1 == -1)
        return s;
    int c = 0;
    char a[100000];int length = 0;
    //对应位置相加
    while (s1 > -1 && t1 > -1) {
        a[length] = (s[s1] - '0' + t[t1] - '0' + c) % 10+'0';
        c = (s[s1] - '0' + t[t1] - '0' + c) / 10;
        length++;
        s1--;
        t1--;
    }
    if (s1 == -1) {
        while (t1 > -1) {
            a[length] = (t[t1] - '0' + c) % 10+'0';
            c = (t[t1] - '0' + c) / 10;
            length++;
            t1--;
        }
    } else {
        while (s1 > -1) {
            a[length] = (s[s1] - '0' + c) % 10+'0';
            c = (s[s1] - '0' + c) / 10;
            length++;
            s1--;
        }
    }
    //最后一位有无进位
    if(c>0){
        a[length] = ('0' + c);
    }else {
        length--;
    }
    char *a1= malloc((length + 1) * sizeof(char));
    int i;
     for (i = length; i >= 0; i--) {
        a1[length-i]=a[i];
    }
    a1[1+length]='\0';
    return a1;
}

全部评论
最初把 length 类型设为了char 类型,对于长的测试案例就无法通过了。 一个有符号的int类型的取值范围是-2,147,483,648到2,147,483,647 一个有符号的char类型在大多数系统中的取值范围是-128到127
点赞 回复 分享
发布于 05-07 15:32 北京

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务