LeetCode-Add Two Numbers
发布时间:2020-12-14 02:41:19 所属栏目:大数据 来源:网络整理
导读:问题描述: 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)
问题描述: 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) 该问题实际上是解决大数相加的一种方法---通过链表来实现大数相加,博主在本科毕业参加一些企业的笔试时就遇到过这个问题。这个问题看似简单,实际上还是有些细节需要注意,主要是进位。 下面是通过测试的代码: /** * 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) { int carry = 0; //进位 int digit = 0; ListNode* head = NULL; ListNode* pre = NULL; ListNode* newNode = NULL; while(l1 !=NULL && l2!=NULL) { digit = (l1->val+l2->val+carry)%10; carry = (l1->val+l2->val+carry)/10; newNode = new ListNode(digit); if (head == NULL) head = newNode; else pre->next = newNode; pre = newNode; l1 = l1->next; l2 = l2->next; } while (l1 != NULL) { digit = (l1->val+carry)%10; carry = (l1->val+carry)/10; newNode = new ListNode(digit); if (head == NULL) head = newNode; else pre->next = newNode; pre = newNode; l1 = l1->next; } while (l2 != NULL) { digit = (l2->val+carry)%10; carry = (l2->val+carry)/10; newNode = new ListNode(digit); if (head == NULL) head = newNode; else pre->next = newNode; pre = newNode; l2 = l2->next; } if(carry>0) { newNode = new ListNode(carry); pre->next = newNode; } return head; } };本文原创,转载请注明! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |