1. 程式人生 > >【leetcode日記】2.Add Two Numbers(c語言)

【leetcode日記】2.Add Two Numbers(c語言)

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

注意邊界: 1.不能將兩個加數從連結串列裡面取出來,加完將和再用連結串列表示,因為這些數可 能會大於int、float、double型的範圍; 2.返回的連結串列,尾巴是否正確指向NULL? 3.推薦測試用例: 0+0=0 5+5=10 9999999991+9=10000000000

struct ListNode* addTwoNumbers(struct ListNode*
l1, struct ListNode* l2) { int num,carry=0,bit; struct ListNode* p1=l1, *p2=l2; struct ListNode* l3 = (struct ListNode*)malloc(sizeof(struct ListNode)); num = (p1->val) + (p2->val); if (num / 10 != 0) carry = 1; bit = num % 10; l3->val = bit; l3->next = NULL; struct ListNode* p3 =
l3; p1 = p1->next; p2 = p2->next; //add while (p1&&p2) { num = (p1->val) + (p2->val)+carry; carry = 0; if (num / 10 != 0) carry = 1; bit = num % 10; struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode)); new_node->val = bit; new_node->next = NULL; p3->next = new_node; p3 = p3->next; p1 = p1->next; p2 = p2->next; } if (p1) { while (carry != 0&&p1!=NULL) { num = (p1->val) + carry; carry = num / 10; bit = num % 10; struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode)); new_node->val = bit; new_node->next = NULL; p3->next = new_node; p3 = p3->next; p1 = p1->next; } if (carry == 0 && p1 == NULL) { p3->next = NULL; return l3; } else if (carry == 0) { p3->next = p1; return l3; } else if (p1 == NULL) { struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode)); new_node->val = 1; new_node->next = NULL; p3->next = new_node; return l3; } } else if (p2) { while (carry != 0 && p2 != NULL) { num = (p2->val) + carry; carry = num / 10; bit = num % 10; struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode)); new_node->val = bit; new_node->next = NULL; p3->next = new_node; p3 = p3->next; p2 = p2->next; } if (carry == 0 && p2 == NULL) { p3->next = NULL; return l3; } else if (carry == 0) { p3->next = p2; return l3; } else if (p2 == NULL) { struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode)); new_node->val = 1; new_node->next = NULL; p3->next = new_node; return l3; } } else if (carry == 1) { struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode)); new_node->val = 1; new_node->next = NULL; p3->next = new_node; } return l3; }