Medium 2题 Add Two Numbers
来源:互联网 发布:淘宝卖家怎么查看总额 编辑:程序博客网 时间:2024/06/05 03:02
Question:
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
Solution:
/** * 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 res=new ListNode(0); ListNode head=res; int sum=0; int carry=0; while(l1!=null||l2!=null||carry!=0) { ListNode cur=new ListNode(0); if(l1!=null) sum+=l1.val; if(l2!=null) sum+=l2.val; cur.val=(sum+carry)%10; if(sum+carry>=10) carry=1;//the carry can only be one else carry=0; res.next=cur; res=cur; sum=0; if(l1!=null) l1=l1.next; if(l2!=null) l2=l2.next; } return head.next; }}
第二遍写就好多了~综合了add two numbers ii
/** * 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) { int carry=0; ListNode head=new ListNode(0); ListNode cur=head; while(l1!=null||l2!=null||carry!=0){ int tmp=0; if(l1!=null) { tmp+=l1.val; l1=l1.next; } if(l2!=null) { tmp+=l2.val; l2=l2.next; } tmp+=carry; carry=tmp/10; ListNode tmpp=new ListNode(tmp%10); cur.next=tmpp; cur=cur.next; } return head.next; }}
0 0
- Medium 2题 Add Two Numbers
- Add Two Numbers [Medium]
- Add Two Numbers(medium)
- [Medium]Add Two Numbers
- Medium 445题 Add Two Numbers II
- Leet Code Medium 2 add two numbers
- <LeetCode><Medium>2 Add Two Numbers
- [2, Medium, C++] Add Two Numbers
- Leetcode #2 Add Two Numbers(medium)
- Leetcode OJ 2 Add Two Numbers [Medium]
- week2-leetcode #2-Add two Numbers[Medium]
- 2. Add Two Numbers Medium
- LeetCode-2-Add Two Numbers(链表)-Medium
- [LeetCode][2 Add Two Numbers][medium]Java实现
- Leetcode 2. Add Two Numbers (Medium) (cpp)
- 2. Add Two Numbers 难度:Medium
- 【leetcode】2. Add Two Numbers 【medium】
- 2. Add Two Numbers(Medium)
- Codeforces Round #377 (Div. 2) C. Sanatorium 分类讨论
- 进阶!Quartz2D对UIImage的常用操作
- Codeforces Round #377 (Div. 2) D. Exams 二分+贪心 or 纯贪心水过
- 8. Java可变参数与foreach
- 190. Reverse Bits
- Medium 2题 Add Two Numbers
- 9. java小节(全排列)
- ORA-00600: 内部错误代码, 参数: [evapls1], [], [], [], [], [], [], []的解决
- oracle 表空间操作语句备忘
- K-means 聚类算法及其代码实现
- Mybatis一对一(多对一)关联表查询
- Hibernate4后出现: org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect'
- 数据库(3-1)
- Spring依赖注入的两种方式