[leetcode]2. Add Two Numbers

2. Add Two Numbers

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
Explanation: 342 + 465 = 807.

这个题目。。我第一反应是。。暴力去解。。于是我就用了一个stack,把链表的元素全拿出来,然后还原成数字,求和,最后再拆分成链表。。结果嘛。。愉快地超时了。。后面发现可以直接求和,再后面发现。。由于输出顺序也是这样倒着的,所以栈也不用了。。。于是就直接求和了,只需要分好类就行。

当有进位的时候,就用一个check做标记,然后当前数字减去10,下一次去和加上去就行。

当两个链表均到了空指针就结束求和。这样分类就可以了。

具体代码如下:

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* answer = new ListNode(0);
		ListNode* move = answer;
		bool check = false;
		int temp_result = 0;
		temp_result = l1->val + l2->val;
		if (temp_result >= 10) {
			check = true;
			temp_result -= 10;
		}

		l1 = l1->next;
		l2 = l2->next;
		move->val = temp_result;

        //当两者均为空指针就结束循环
		while (l1 != NULL || l2 != NULL) {
			ListNode* newblock = new ListNode(0);
			temp_result = 0;

            //如果有进位,就加1
			if (check == true) {
				temp_result += 1;
			}

            //分为三类,单分别单一空指针、非空指针均进行处理
			if (l1 == NULL) {
				temp_result += l2->val;
				l2 = l2->next;
			}
			else if (l2 == NULL) {
				temp_result += l1->val;
				l1 = l1->next;
			}
			else {
				temp_result += l1->val + l2->val;
				l1 = l1->next;
				l2 = l2->next;
			}

            //如果有进位,当前数字 -10,标记设置为true
			if (temp_result >= 10) {
				check = true;
				temp_result -= 10;
			}
			else check = false;

			move->next = newblock;
            move = move->next;
			move->val = temp_result;
		}

        //如果最后一位进位,则新加一个块去储存
		if (check == true) {
			ListNode* newblock = new ListNode(0);
			move->next = newblock;
            move = move->next;
			move->val = 1;
		}
		return answer;
	}
};

这几天刷了好几题 我均尝试了暴力的方法。。基本都超时了。。。看来还是要慎用了,毕竟很多题目看得出出题者是不希望你用暴力手段去解的。。。下次要注意点了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值