Leetcode Exercise
来源:互联网 发布:网络电子游戏官网 编辑:程序博客网 时间:2024/04/30 13:31
Question: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
Answer
/** * 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 lNode=new ListNode(0); ListNode origin=lNode; int carry=0; while(l1!=null&&l2!=null){ if(l1.val+l2.val+carry<10){ lNode.val=l1.val+l2.val+carry; carry=0; }else{ lNode.val=(l1.val+l2.val+carry)%10; carry=1; } l1=l1.next; l2=l2.next; if(l1!=null&&l2!=null){ lNode.next=new ListNode(0); lNode=lNode.next; } } if(l1==null&&l2==null){ if(carry==0){ return origin; }else{ lNode.next=new ListNode(1); lNode=null; } } if(l1!=null){ lNode.next=new ListNode(0); lNode=lNode.next; while(l1!=null){ if(l1.val+carry<10){ lNode.val=l1.val+carry; carry=0; }else{ lNode.val=(l1.val+carry)%10; carry=1; } l1=l1.next; if(l1!=null){ lNode.next=new ListNode(0); lNode=lNode.next; } } if(carry==1){ lNode.next=new ListNode(1); lNode=null; } } if(l2!=null){ lNode.next=new ListNode(0); lNode=lNode.next; while(l2!=null){ if(l2.val+carry<10){ lNode.val=l2.val+carry; carry=0; }else{ lNode.val=(l2.val+carry)%10; carry=1; } l2=l2.next; if(l2!=null){ lNode.next=new ListNode(0); lNode=lNode.next; } } if(carry==1){ lNode.next=new ListNode(1); lNode=null; } } return origin; }}
0 0
- Leetcode Exercise
- Leetcode Exercise
- Leetcode Exercise
- LeetCode Exercise 4: Next Permutation
- LeetCode Exercise 6: Remove Element
- LeetCode Exercise 7: Group Anagrams
- LeetCode Exercise 10: Merge Intervals
- LeetCode Exercise 11: Spiral Matrix
- LeetCode Exercise 14: Maximal Square
- LeetCode Exercise 15: Summary Ranges
- Exercise
- exercise
- Exercise
- exercise
- Leetcode Exercise 1:Two Sum + Three Sum
- LeetCode Exercise 5: Trapping Rain Water
- LeetCode Exercise 9: Minimum Path Sum
- LeetCode Exercise 12:Minimum Size Subarray Sum
- HDU 3478
- 第一章 绪论
- JS将一个十进制转换成二进制
- 生成所有的出栈序列 (回溯法)
- myql5.7.7优化配置参数
- Leetcode Exercise
- 给dubbo接口添加白名单——dubbo Filter的使用
- Android网络编程
- 排序算法之快速排序
- 线段树 csu1555 Inversion Sequence
- Axsure中变量的使用
- 周赛一 ACdream 1204 模拟
- uva 639
- Cookie V.S. Session