C语言 | Leetcode C语言题解之第415题字符串相加

题目:

题解:

cpp 复制代码
char* addStrings(char* num1, char* num2) {
    int i = strlen(num1) - 1, j = strlen(num2) - 1, add = 0;
    char* ans = (char*)malloc(sizeof(char) * (fmax(i, j) + 3));
    int len = 0;
    while (i >= 0 || j >= 0 || add != 0) {
        int x = i >= 0 ? num1[i] - '0' : 0;
        int y = j >= 0 ? num2[j] - '0' : 0;
        int result = x + y + add;
        ans[len++] = '0' + result % 10;
        add = result / 10;
        i--, j--;
    }
    // 计算完以后的答案需要翻转过来
    for (int i = 0; 2 * i < len; i++) {
        int t = ans[i];
        ans[i] = ans[len - i - 1], ans[len - i - 1] = t;
    }
    ans[len++] = 0;
    return ans;
}
相关推荐
AlenTech3 小时前
141. 环形链表 - 力扣(LeetCode)
数据结构·leetcode·链表
dulu~dulu4 小时前
算法---寻找和为K的子数组
笔记·python·算法·leetcode
佑白雪乐4 小时前
<ACM进度212题>[2026-3-1,2026-3-26]
算法·leetcode
穿条秋裤到处跑4 小时前
每日一道leetcode(2026.03.26):等和矩阵分割 II
算法·leetcode·矩阵
平凡灵感码头4 小时前
C语言 printf 数据打印格式速查表
c语言·开发语言·算法
x_xbx5 小时前
LeetCode:1. 两数之和
数据结构·算法·leetcode
x_xbx5 小时前
LeetCode:49. 字母异位词分组
算法·leetcode·职场和发展
努力中的编程者6 小时前
二叉树(C语言底层实现)
c语言·开发语言·数据结构·c++·算法
爱编码的小八嘎6 小时前
C语言完美演绎5-3
c语言
山川行6 小时前
关于《项目C语言》专栏的总结
c语言·开发语言·数据结构·vscode·python·算法·visual studio code