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

2.ADD TWO Numbers

时间:2017-10-25 00:46:37      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:head   c++   repr   may   list   blog   car   elf   code   

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 直接从左边到右边依次把两单链表相加,注意进位。
 
-------------------------JAVA-----------------------------------------
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummyHead;
    int carry = 0;
    while (p != null || q != null) {
        int x = (p != null) ? p.val : 0;       //节点存在,则为节点值;节点为空,则置为0
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;               //两数相加,且加上低位的进位
        carry = sum / 10;                     //进位
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);        //最高位
    }
    return dummyHead.next;
}

 


 
——————————————————————————————( C++ )————————————————————
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* pRoot = NULL;
        
        do {
            if (l1 == NULL) {
                pRoot = l2;
                break;
            } 
            
            if (l2 == NULL) {
                pRoot = l1;
                break;
            }
            
            int sum = l1->val + l2->val;
            int digit = sum % 10;                    //如sum=12,digit=2
            int carry = sum / 10;                   //如sum=12,进位等于1
            pRoot = new ListNode(digit);
            ListNode* pTail = pRoot;
            l1 = l1->next;
            l2 = l2->next;

            while (l1 != NULL || l2 != NULL) {
                int sum = ((l1 != NULL) ? l1->val : 0) + ((l2 != NULL) ? l2->val : 0) + carry;
                int digit = sum % 10;
                l1 = l1 != NULL ? l1->next : NULL;
                l2 = l2 != NULL ? l2->next : NULL;
            }
            
            if (carry == 1) {
                ListNode* pNew = new ListNode(carry);
                pTail->next = pNew;
            }
        } while (false);
        
        return pRoot;
    }
};

  



2.ADD TWO Numbers

标签:head   c++   repr   may   list   blog   car   elf   code   

原文地址:http://www.cnblogs.com/hozhangel/p/7726412.html

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