LeetCode-Add Two Numbers-解题报告

原创 2015年07月08日 21:31:09

原题链接 https://leetcode.com/problems/add-two-numbers/

You are given two linked lists representing two non-negative numbers. 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.

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


水过


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
		if (l1 == NULL)return l2;
		if (l2 == NULL)return l1;
		ListNode *ans, *tmp, *head;
		int c = 0, flag = 0;
		for (; l1 != NULL || l2 != NULL;)
		{
			int a = 0, b = 0;
			if (l1 != NULL)a = l1->val;
			if (l2 != NULL)b = l2->val;
			a = a + b + c;
			c = a / 10;
			a = a % 10;
			tmp = new ListNode(a);
			if (flag == 0)ans = tmp, flag = 1, head = tmp;
			else head->next = tmp, head = head->next;
			if (l1 != NULL)l1 = l1->next;
			if (l2 != NULL)l2 = l2->next;
		}
		if (c)
			tmp = new ListNode(c), head->next = tmp;
		return ans;
	}
};


版权声明:

相关文章推荐

leetcode解题报告2. Add Two Numbers

leetcode解题报告2. Add Two Numbers题目地址 难度是medium题目描述用单链表来表示一个大整数,其中单链表的每个节点只有一个数0~9。给两个这样单链表表示的整数,求它们的和(...

[LeetCode] Add Two Numbers 解题报告

—— write for my baby, mua [题目] You are given two linked lists representing two non-negative numb...

【LeetCode】2. Add Two Numbers 解题报告

转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51820937Subject 出处:https://leetcode.com/pro...

LeetCode 2. Add Two Numbers 解题报告

LeetCode 2. Add Two Numbers 解题报告题目描述You are given two non-empty linked lists representing two non-ne...

LeetCode 2. Add Two Numbers 解题报告

题意: 有两个链表,它们表示逆序的两个非负数。例 (2 -> 4 -> 3)表示342,求两个数字的和,并用同样的方式逆序输出。如342+465 = 807,你需要把结果表达为(7 ->0 ->8)...

LeetCode 421 Maximum XOR of Two Numbers in an Array 解题报告

一道有意思的题目, 用到了异或运算的一个小特性. LeetCode 421 Maximum XOR of Two Numbers in an Array. Given a non-empty arra...

Leetcode #2 Add Two Numbers 解题小结

1 题外话我又回来更新Leetcode了,现在准备有空做做leetcode,等着用java刷完以后再切换到其他语言试试吧~~。 2 题目理解[原题](https://leetcode.com/prob...

【Leetcode】2.Add Two Numbers 解题

You are given two linked lists representing two non-negative numbers. The digits are stored in rever...

[leetcode] 211. Add and Search Word - Data structure design 解题报告

题目链接: https://leetcode.com/problems/add-and-search-word-data-structure-design/ Design a data struc...

[Leetcode] 211. Add and Search Word - Data structure design 解题报告

题目: Design a data structure that supports the following two operations: void addWord(word) boo...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)