LeetCode题解 第二周

来源:互联网 发布:网络语言99是什么意思 编辑:程序博客网 时间:2024/06/04 18:19

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








原创粉丝点击