首页 > 其他 > 详细

2.Add Two Numbers

时间:2017-02-26 23:37:54      阅读:307      评论:0      收藏:0      [点我收藏+]

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

  • Difficulty: Medium

简单解释一下题意,两个位置颠倒(例如:892写成298)的数字相加后,按正常顺序输出结果。

解题思路:

1.从左到右开始互加计算,倘若在某位相加和大于等于10,要向右一位加1,而不是左一位加1.

2.题目要求返回的是链表,所以每进位得到的结果可以通过头插法插入到链表首位,最后得到题目要求的正常顺序的结果

 

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
          ListNode* head = new ListNode(0);
          ListNode* res = head;
          int tmp = 0;
          while(l1||l2||res){
             int num = (l1? l1->val:0) + (l2? l2->val:0) + tmp;
             tmp = num / 10;
             res->next = new ListNode(num % 10);
             res = res->next;
             if(l1) l1 = l1->next;
             if(l2) l2 = l2->next;
          }
          return head->next;

}

 

2.Add Two Numbers

原文:http://www.cnblogs.com/sarahp/p/6456085.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!