LeetCode 2 — Add Two Numbers(C++ Java Python)

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/dragon_dream/article/details/19544995

题目:http://oj.leetcode.com/problems/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

题目翻译:

给定两个链表表示两个非负数。数字逆序存储,每个节点包含一个单一的数字。计算两个数的和,并以链表的形式返还。

分析:

        要考虑进位。表示结果的结点要new出来。

C++实现:

/**
 * 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) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.

		if (l1 == NULL)
		{
			return l2;
		}
		if (l2 == NULL)
		{
			return l1;
		}

		ListNode *result = NULL;
		ListNode *sum = NULL;

		int val = 0;
		int carry = 0;

		while (l1 != NULL || l2 != NULL)
		{
			val = carry;
			if (l1 != NULL)
			{
				val += l1->val;
			}
			if (l2 != NULL)
			{
				val += l2->val;
			}

			carry = val / 10;
			val -= carry * 10;

			if (sum == NULL)
			{
				sum = new ListNode(val);
				result = sum;
			}
			else
			{
				sum->next = new ListNode(val);
				sum = sum->next;
			}

			if (l1 != NULL)  
			{
				l1 = l1->next;
			}
			if (l2 != NULL)
			{
				l2 = l2->next;
			}
		}

		if (carry != 0)
		{
			sum->next = new ListNode(carry);
		}

		return result;
    }
};

Java实现:(与C++实现不太一样)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
		if (l1 == null) {
			return l2;
		}
		if (l2 == null) {
			return l1;
		}

		int len1 = 0;
		int len2 = 0;

		ListNode head = l1;

		while (head != null) {
			++len1;
			head = head.next;
		}

		head = l2;

		while (head != null) {
			++len2;
			head = head.next;
		}

		ListNode longer = len1 >= len2 ? l1 : l2;
		ListNode shorter = len1 < len2 ? l1 : l2;

		ListNode result = null;
		ListNode sum = null;

		int val = 0;
		int carry = 0;

		while (shorter != null) {
			val = longer.val + shorter.val + carry;
			carry = val / 10;
			val -= carry * 10;
			
			if (sum == null) {
				sum = new ListNode(val);
				result = sum;
			} else {
				sum.next = new ListNode(val);
				sum = sum.next;
			}
			
			longer = longer.next;
			shorter = shorter.next;
		}

		while (longer != null) {
			val = longer.val + carry;
			carry = val / 10;
			val -= carry * 10;
			
			sum.next = new ListNode(val);
			sum = sum.next;
			
			longer = longer.next;
		}

		if (carry != 0) {
			sum.next = new ListNode(carry);
		}

		return result;
    }
}

Python实现:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
        if l1 == None:
            return l2
        if l2 == None:
            return l1
        
        len1 = 0
        len2 = 0
        
        head = l1
        while head != None:
            len1 += 1
            head = head.next
        
        head = l2
        while head != None:
            len2 += 1
            head = head.next
        
        if len1 >= len2:
            longer = l1
            shorter = l2
        else:
            longer = l2;
            shorter = l1
        
        sum = None
        
        carry = 0
        
        while shorter != None:
            value = longer.val + shorter.val + carry
            carry = value / 10
            value -= carry * 10
            
            if sum == None:
                sum = ListNode(value)
                result = sum
            else:
                sum.next = ListNode(value)
                sum = sum.next
                
            longer = longer.next
            shorter = shorter.next
            
        while longer != None:
            value = longer.val + carry
            carry = value / 10
            value -= carry * 10
            
            sum.next = ListNode(value)
            sum = sum.next
            
            longer = longer.next
            
        if carry != 0:
            sum.next = ListNode(carry)
        
        return result

        感谢阅读,欢迎评论!

展开阅读全文

Add Two Numbers的问题

08-02

求助,LeetCode OJ 上的第二题Add Two Numbers,不熟练链表的我卡在这儿了,两个被加数位数相同算法没问题,位数不相同执行就当了。。。。一直没看出什么问题,调试器只有gdb,不会用。求大神帮忙看看是什么问题,跪谢。rnrn/*Add two numbersrn You are given two linked lists representing two non-negative numbers. rn The digits are stored in reverse order and each of their nodes contain a single digit. rn Add the two numbers and return it as a linked list.rn rn Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)rn Output: 7 -> 0 -> 8rn*/rnrn//定义简单结点rnstruct ListNode rn int val;rn ListNode *next;rn ListNode(int x) : val(x), next(NULL) rn;rnrn//创建解决方案rnclass Solution rnpublic:rn ListNode* addTwoNumbers( ListNode* l1, ListNode* l2 ) rn ListNode *pHead , *pCurr; //定义头指针 , 当前指针rn int sum , val1 , val2 , carry; //定义和,被加数1,被加数2,进位数rn pHead = ( ListNode * )malloc( sizeof( ListNode ) ); //创建第一个结点rn pCurr = pHead; //初始化当前结点rn carry = 0; //初始化进位数rn while( l1 != NULL || l2 != NULL ) //循环直到两个被加数的当前指针都为空rn rn val1 = l1 != NULL ? l1->val : 0; //为被加数赋值rn val2 = l2 != NULL ? l2->val : 0;rn rn sum = ( val1 + val2 + carry ) % 10; //求和rn carry = ( val1 + val2 + carry ) / 10; //求进位rn rn pCurr->val = sum; //为储存结果的链表添加数字rn if ( l1->next != NULL || l2->next != NULL) //储存结果的链表添加下一个结点rn pCurr->next = ( ListNode * )malloc( sizeof( ListNode ) );rn pCurr = pCurr->next;rn rn rn if ( l1 != NULL ) //被加数指针下移rn l1 = l1->next;rn rn if ( l2 != NULL )rn l2 = l2->next;rn rn rn rn if ( carry != 0) //循环结束进位结算rn pCurr->next = ( ListNode * )malloc( sizeof( ListNode ) );rn pCurr = pCurr->next;rn pCurr->val = carry;rn rn rn pCurr->next = NULL;rn rn return pHead; //输出结果rn rn; 论坛

没有更多推荐了,返回首页