Leetcode---2.Add Two Numbers

来源:互联网 发布:域名怎么和服务器绑定 编辑:程序博客网 时间:2024/06/16 19:47

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.
    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8

  • 分析:
    这道题其实是通过链表实现加法运算,上述例子对应着342+465=807。编程实现需要考虑以下几个因素:
    (1) 两个数组为空的情况,题目中说明链表非空,所以这条不考虑。
    (2) 当两个数组的长度不一样时,应如何处理。
    (3) 低位向高位的进位如何处理。
    (4) 最高位也可能产生进位,该如何处理,例如:456+632=1088。
    综合考虑以上情况,采用以下的方法:

/** * 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) {        //定义一个指向结果链表的指针        ListNode * ret=(ListNode *)malloc(sizeof(ListNode));        ListNode * p=ret;        //up表示进位        //sum表示l1和l2每一位的求和        //val1、val2用来存取每一位上的val        int up=0,sum,val1,val2;        //up!=0 处理最高位产生进位的情况        while(l1!=NULL||l2!=NULL||up!=0){            val1=(l1==NULL?0:l1->val);            val2=(l2==NULL?0:l2->val);            //l1、l2对应位求和(注意要加上低位产生的进位)            sum=val1+val2+up;            //计算进位            up=sum/10;            //新建一个Node            ListNode * node= (ListNode *)malloc(sizeof(ListNode));            node->val=sum%10;            node->next=NULL;            //尾插法            p->next=node;            p=node;            //更新l1,l2            l1=(l1==NULL?NULL:l1->next);            l2=(l2==NULL?NULL:l2->next);        }        return ret->next;    }};
原创粉丝点击