两数相加

问题
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

C#代码

/**
* Definition for singly-linked list.
* public class ListNode {
*     public int val;
*     public ListNode next;
*     public ListNode(int x) { val = x; }
* }
*/
public class Solution
{
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
    {
        ListNode res, tmp1, tmp2, tmpRes;
        int tmpSum = 0, tmpCarry = 0;

        tmpSum = l1.val + l2.val;
        tmpCarry = tmpSum / 10;
        res = new ListNode(tmpSum % 10);
        tmp1 = l1.next;
        tmp2 = l2.next;
        tmpRes = res;

        while (!((tmp1 == null) && (tmp2 == null)))
        {
            tmpSum = ((tmp1 == null) ? 0 : tmp1.val) + ((tmp2 == null) ? 0 : tmp2.val) + tmpCarry;
            tmpCarry = tmpSum / 10;
            tmpRes.next = new ListNode(tmpSum % 10);

            tmp1 = (tmp1 == null) ? null : tmp1.next;
            tmp2 = (tmp2 == null) ? null : tmp2.next;
            tmpRes = tmpRes.next;
        }

        if (tmpCarry > 0)
            tmpRes.next = new ListNode(tmpCarry);
        return res;
    }
}

小结
不可以直接计算,会造成越界,按位相加

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值