首页 > 其他 > 详细

LeetCode-Add Two Numbers

时间:2015-03-27 20:05:55      阅读:281      评论: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

原题地址:https://leetcode.com/problems/add-two-numbers/


该问题实际上是解决大数相加的一种方法---通过链表来实现大数相加,博主在本科毕业参加一些企业的笔试时就遇到过这个问题。这个问题看似简单,实际上还是有些细节需要注意,主要是进位。

下面是通过测试的代码:

/**
 * 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;
    }
};

本文原创,转载请注明!

LeetCode-Add Two Numbers

原文:http://blog.csdn.net/computerme/article/details/44679729

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