2. Add Two Numbers
来源:互联网 发布:mac系统自动重装系统 编辑:程序博客网 时间:2024/05/23 00:09
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
package November;public class AddTwoNumbers {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {ListNode result=new ListNode(0);addTwoNumbers(l1,l2,result);return result;}public void addTwoNumbers(ListNode l1, ListNode l2,ListNode res_tmp) {int carry=0;while (l1 != null || l2 != null) {//考虑判断条件,如果分别加两个循环,没有这个简洁int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val)//考虑判断条件+ carry;//考虑carryint current = sum % 10;carry = sum / 10;res_tmp.val = current;if (l1 != null) {//conditionl1 = l1.next;}if (l2 != null) {//conditionl2 = l2.next;}if (l1 != null || l2 != null || carry != 0) {//conditionres_tmp.next = new ListNode(0);res_tmp = res_tmp.next;}}if(carry!=0){//conditionres_tmp.val=carry;res_tmp.next=null;}}public class ListNode {int val;ListNode next;ListNode(int x) {val = x;}}}
阅读全文
0 0
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- HTML5新增input输入的list属性的使用
- Generative Adversarial Nets (GAN) 阅读笔记
- spring+Thymeleaf中文编码的问题
- 算法导论-第七章快速排序
- PhotoShop CC 2017软件工具面板使用---索套工具
- 2. Add Two Numbers
- Vue学习总结(一)
- Java的流程控制
- 生成对抗网络GAN(一) 简介和变种
- Mysql| limit限制结果范围(LIMIT,OFFSET )
- 2.数组a[N]中,随机存放了1至N-1的数,再加入一个数,这个数和之前的n-1其中某个数重复。写一个函数,找出被重复的数字.时间复杂度必须为o(N
- React通过父组件传递类名给子组件的方法
- DLL的创建与使用
- Could not read JSON: Can not deserialize instance of out of START_ARRAY token