Add Two Numbers || LeetCode-2
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
<问题描述>
>>>>给定两个非负整形的非空链表,整数的每一位以相反的顺序存储在链表中
>>>>你可以假定两个整数都没有前导的零
>>>>给出的addTwoNumbers函数应该以链表形式返回两个整数的和
>>>>输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
>>>>输出:7 -> 0 -> 8
Approach #Solution
Analysis
本题思路很简单,按照加法原理从末尾到首位,每一位对齐相加即可。关键在于如何处理不同长度的数字,以及进位和最高位的判断。若有一个为null时,返回不为null的那个ListNode和进位相加的值;若都不为null时,返回两个ListNode和进位相加的值。
Code
Complexity
>>>>时间复杂度:O(n)
>>>>时间复杂度:O(n)
Code:https://github.com/JyNeo/LeetCode/blob/master/Solution002.java