Leetcode_Add Two Numbers
来源:互联网 发布:大数据培训学校 编辑:程序博客网 时间:2024/05/16 15:21
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
已下是java实现:
1、已知下列ListNode的数据结构
public static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } }2、方法如下:
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {int add = 0;//存储进位int res = 0;//存储每一位相加的结果ListNode ln = new ListNode(0);ListNode key = ln;//key是当前节点while(l1!=null && l2!=null){//处理l1、l2都不为空的情况res = l1.val+l2.val+add;if(res>9){add=1;res=res-10;}else{add=0;}ListNode temp = new ListNode(res);key.next=temp;key=temp;l1=l1.next;l2=l2.next;}if(l1!=null){//处理只剩l1的情况while(l1!=null){res = l1.val+add;if(res>9){add=1;res=res-10;}else{add=0;}ListNode temp = new ListNode(res);key.next=temp;key=temp;l1=l1.next;}}else if(l2!=null){//处理只剩l2的情况while(l2!=null){res = l2.val+add;if(res>9){add=1;res=res-10;}else{add=0;}ListNode temp = new ListNode(res);key.next=temp;key=temp;l2=l2.next;}}if(add==1){//处理最后一位有进位的情况ListNode temp = new ListNode(1);key.next=temp;key=temp;}return ln.next; }
3、写一个测试主方法
public static void main(String[] args) {ListNode l1 = new ListNode(2) ;l1.next=new ListNode(8);ListNode l2 = new ListNode(5) ;l2.next=new ListNode(9);l2.next.next=new ListNode(9);ListNode ln =addTwoNumbers(l1,l2);while(ln!=null){System.out.println(ln.val+"------");ln=ln.next;}}
4、相当于
Input: (2 -> 8) + (5 -> 9 -> 9)
Output: 7 -> 7 -> 0- > 1
0 0
- Leetcode_Add Two Numbers
- leetcode_Add Two Numbers
- LeetCode_Add Two Numbers
- Leetcode_Add Two Numbers
- LeetCode_Add Two Numbers
- LeetCode_Add Two Numbers
- LeetCode_Add Two Numbers(Medium)
- leetcode_add two nums
- leetcode_add two number
- Two Numbers
- Two Sum & Add Two Numbers
- 题Two--Add Two Numbers
- LeetCode: Add Two Numbers
- Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- 【技巧】android中ListView拉黑解决方法
- 【AJAX好学易用系列】之二:XMLHttpRequst对象
- hdu 1072(倒计时bfs)
- 二叉树的递归遍历
- 关于spring mvc Controller的几个注解
- Leetcode_Add Two Numbers
- c++ 如何获取系统时间
- Android View的加载过程
- windows internals - 读书笔记一
- 不要被阶乘吓到
- Java实现Base64加密
- (行为型模式三)观察者模式
- WebService设计原则
- 纪念汪国真先生