leetcode 2. Add Two Numbers
2017-05-11 14:50
417 查看
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p=l1,q=l2;
ListNode head=new ListNode(-1);
ListNode hp=head;
int plus=0;
int carry=0;
while(p!=null&&q!=null){
plus=p.val+q.val+carry;
ListNode ln=new ListNode(plus%10);
ln.next=null;
hp.next=ln;
hp=ln;
carry=plus/10;
p=p.next;
q=q.next;
}
while(p!=null){
plus=p.val+carry;
ListNode ln=new ListNode(plus%10);
ln.next=null;
hp.next=ln;
hp=ln;
carry=plus/10;
p=p.next;
}
while(q!=null){
plus=q.val+carry;
ListNode ln=new ListNode(plus%10);
ln.next=null;
hp.next=ln;
hp=ln;
carry=plus/10;
q=q.next;
}
if(carry!=0){
ListNode ln=new ListNode(carry);
ln.next=null;
hp.next=ln;
hp=ln;
}
return head.next;
}
}
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p=l1,q=l2;
ListNode head=new ListNode(-1);
ListNode hp=head;
int plus=0;
int carry=0;
while(p!=null&&q!=null){
plus=p.val+q.val+carry;
ListNode ln=new ListNode(plus%10);
ln.next=null;
hp.next=ln;
hp=ln;
carry=plus/10;
p=p.next;
q=q.next;
}
while(p!=null){
plus=p.val+carry;
ListNode ln=new ListNode(plus%10);
ln.next=null;
hp.next=ln;
hp=ln;
carry=plus/10;
p=p.next;
}
while(q!=null){
plus=q.val+carry;
ListNode ln=new ListNode(plus%10);
ln.next=null;
hp.next=ln;
hp=ln;
carry=plus/10;
q=q.next;
}
if(carry!=0){
ListNode ln=new ListNode(carry);
ln.next=null;
hp.next=ln;
hp=ln;
}
return head.next;
}
}
相关文章推荐
- 【Leetcode】【python】Add Two Numbers
- 【Leetcode】Add Two Numbers
- leetcode--Add Two Numbers
- Leetcode: Add Two Numbers
- 【leetcode】【2】Add Two Numbers
- Leetcode 线性表 数 Add Two Numbers
- leetcode-2-Add Two Numbers
- leetcode Add Two Numbers
- leetcode Add Two Numbers
- LeetCode——2. Add Two Numbers
- 【LeetCode】Add Two Numbers
- [Leetcode 2, Medium] Add Two Numbers
- 【LeetCode解答二】Add Two Numbers问题Java解答
- LeetCode习题笔记——Add Two Numbers
- LeetCode题解 #2 Add Two Numbers
- leetcode2--Add Two Numbers
- LeetCode 2. Add Two Numbers
- [leetcode]Add Two Numbers
- leetcode 2. Add Two Numbers python实现的理解,结点,单链表的应用,大数,进位的问题
- leetcode Add Two Numbers