LeetCode题解 第二周

1.Add Two Numbers

https://leetcode.com/problems/add-two-numbers/description/


You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Difficulty:Medium


Explanation:

1、两个链表中的每个节点依次相加,最后将所得的结果储存在一个新的链表之中。对于这个题目,可以参照数字电路里面的加法器的设计思路,让两个数的每位上的数字和进位相加(如果前一个数位上的数字相加没有进位的话进位为零),如果结果大于10则设置进位为1,否则设置进位为0,然后把计算结果的个位数储存到结果链表。如此循环计算,直至两个链表中的每个数位都进行了相加操作。

code:

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
		int carry;
		ListNode* temp1 = l1;
		ListNode* temp2 = l2;
		ListNode* solution = new ListNode(0);
		ListNode* temp3 = solution;
		carry = 0;
		while (temp1 != NULL||temp2 != NULL)
		{
			int sum;
			if (temp1 == NULL)
			{
				sum = temp2->val + carry;
			}
			else if (temp2 == NULL)
			{
				sum = temp1->val + carry;
			}
			else
			{
				sum = temp1->val + temp2->val + carry;
			}
			temp3->val = sum % 10;
			carry = sum / 10;
            		if(temp1!=NULL)
            		{
                		temp1 = temp1->next;
            		}
            		if(temp2!=NULL)
            		{
				temp2 = temp2->next;                
           		 }
			if (temp1 != NULL||temp2 != NULL)
			{
				temp3->next = new ListNode(0);
				temp3=temp3->next;
			}
		}
        if(carry==1)
        {
            temp3->next=new ListNode(1);
        }
		return solution;
	}
};

Attention:需要注意的是,进行相加操作的两个链表可能长度并不相同,所以分情况讨论每次相加时是不是两个链表都已经到达了尾部。








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值