码迷,mamicode.com
首页 > 其他好文 > 详细

Add Two Numbers

时间:2015-04-13 22:27:22      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

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)
Output: 7 -> 0 -> 8

struct ListNode {
    int val;
     ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

/*
    最直白的想法就是将两个字符串翻转, 然后相加,得到的结果再发转
    现在的解法,直接从左到右相加,然后向右进位
*/

class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        
        ListNode* ptr = new ListNode(0);  
        ListNode* head = ptr; 
        int tmp_carry = 0;
        int sum;

        while( l1 || l2 )
        {
             sum = 0;
             if( l1 )
             {
                sum += l1->val;
                l1 = l1->next;
             }

             if( l2 )
             {
                sum += l2->val;
                l2 = l2->next;
             }
        
             ptr->next = new ListNode( (sum + tmp_carry)%10 );  
             ptr = ptr->next;
             tmp_carry = (sum + tmp_carry)/10;
        }

        if( tmp_carry )
        {
             ptr->next = new ListNode( tmp_carry );  
        }
        return head->next;
    }
};

 

Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/aceg/p/4423425.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!