LintCode 655: Add Strings

本文详细介绍了如何使用C++和C语言解决两个非负整数相加的问题,其中整数以字符串形式给出。通过逐位相加并处理进位,实现了不使用内置大数库或直接转换为整数的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

655. Add Strings

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Example

Example 1:

Input : num1 = "123", num2 = "45"

Output : "168"

Notice

The length of both num1 and num2 is < 5100.

Both num1 and num2 contains only digits 0-9.

Both num1 and num2 does not contain any leading zero.

You must not use any built-in BigInteger library or convert the inputs to integer directly.

解法1:

class Solution {
public:
    /**
     * @param num1: a non-negative integers
     * @param num2: a non-negative integers
     * @return: return sum of num1 and num2
     */
    string addStrings(string &num1, string &num2) {
        //return to_string(stoi(num1) + stoi(num2));
        int n1 = num1.size();
        int p1 = n1 - 1;
        int n2 = num2.size();
        int p2 = n2 - 1;
        int sum = 0, carry = 0;
        string result = "";
        
        while(p1 >= 0 && p2 >= 0) {
            sum = num1[p1] - '0' + num2[p2] - '0' + carry;
            carry = sum / 10;
            result = to_string(sum % 10) + result;
            p1--; p2--;
        }

        int p = -1; string num;
        if (p1 >= 0) {
            p = p1; num = num1;
        } else if (p2 >= 0) {
            p = p2; num = num2;
        }
        
        if (p < 0) return carry > 0 ? '1' + result : result;
         
        while (p >= 0) {
            sum = num[p] - '0' + carry;
            carry = sum / 10;
            result = to_string(sum % 10) + result;
            p--;
        }

        return carry > 0 ? '1' + result : result;
    }
};

发一个C的版本
 

#define MAX(a, b) (a > b ? a : b)
char* addStrings(char* num1, char* num2) {
    int len1 = (int)strlen(num1), len2 = (int)strlen(num2);
    int len3 = MAX(len1, len2) + 2;
    int index1 = len1 - 1, index2 = len2 - 1, index3 = len3 - 2;
    int carry = 0, sum = 0;
    char *res = (char *)malloc(len3);
    memset(res, 0, len3);
    while (index1 >= 0 || index2 >= 0) {
        sum = carry;
        if (index1 >= 0) sum += num1[index1--] - '0';
        if (index2 >= 0) sum += num2[index2--] - '0';
        carry = sum / 10;
        res[index3--] = '0' + (sum % 10);
    }
    if (carry > 0) {
        res[index3--] = '1';
    }
    if (res[0] == 0) return &res[1];
    return res;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值