标签:sign lse png class 题目 测试用例 直接 最优 rds
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
int carry = 0;
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int l1Length = 0;
int l2Length = 0;
ListNode l1Tmp = l1;
ListNode l2Tmp = l2;
while(l1!=null){
l1Length++;
l1 = l1.next;
}
while(l2!=null){
l2Length++;
l2 = l2.next;
}
ListNode tmp;
if(l1Length>=l2Length){
tmp= addPlus(l1Tmp,l2Tmp,l1Length-l2Length);
}else{
tmp= addPlus(l2Tmp,l1Tmp,l2Length-l1Length);
}
if(carry!=0){
ListNode head = new ListNode(carry);
head.next = tmp;
tmp = head;
}
return tmp;
}
public ListNode addPlus(ListNode l1,ListNode l2,int length) {
if(l1==null&&l2==null)
return null;
ListNode tmp;
if(length!=0){
tmp = addPlus(l1.next,l2,length-1);
}else{
tmp = addPlus(l1.next, l2.next,0);
}
int sum = (l1==null?0:l1.val)+(l2==null||length!=0?0:l2.val)+carry;
ListNode head = new ListNode(sum%10);
head.next = tmp;
carry = sum /10;
return head;
}
}
效率还可以,但是代码有一点臃肿。
leetcode 445. Add Two Numbers II
标签:sign lse png class 题目 测试用例 直接 最优 rds
原文地址:https://www.cnblogs.com/clnsx/p/12252157.html