微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

LeetCode-Add Two Numbers


问题描述:

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;
    }
};
本文原创,转载请注明!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐