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;
}
相关推荐
dear_bi_MyOnly6 分钟前
栈和队列:从原理到应用全解析
c语言·开发语言·c++·学习·分类
从小白到软工1 小时前
4-3 项目-学生成绩管理系统(上)
c语言·开发语言·数据结构·经验分享·ai编程
Code_Solitude2 小时前
c语言:指针(3)+冒泡排序
java·c语言·算法
巴巴媛6662 小时前
【Debug1】程序死机,while(1)循环,怎么办?
c语言·笔记·stm32·嵌入式硬件·bug
Lxx_Zw2 小时前
PID 用顺了,然后呢:增强手术与前馈
c语言·stm32·单片机·嵌入式硬件
alphaTao3 小时前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
BeiGuTing_code3 小时前
C链表基础(二)有视频模拟!!!
c语言·链表·音视频
Cccp.1234 小时前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
学逆向的4 小时前
C 选择结构的执行效率分析
c语言·开发语言·算法·网络安全
Pniubi4 小时前
力扣70爬楼梯
数据结构·算法·leetcode