LeetCode : Add Two Numbers [java]
来源:互联网 发布:win读取mac硬盘软件 编辑:程序博客网 时间:2024/05/01 21:27
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
思路:按链表顺序,依次相加,进位进到下一个节点元素,最后有进位的,追加一个节点元素。
/** * 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 over = 0;int num1 = 0;int num2 = 0;ListNode head = new ListNode(0);ListNode p = head;while (l1 != null || l2 != null) {if (l1 != null) {num1 = l1.val;l1 = l1.next;}if (l2 != null) {num2 = l2.val;l2 = l2.next;}int sum = num1 + num2 + over;over = sum / 10;ListNode node = new ListNode(sum % 10);p.next = node;p = p.next;num1 = 0;num2 = 0;}if (over != 0) {ListNode node = new ListNode(over);p.next = node;}return head.next; }}
1 0
- [Leetcode] Add Two Numbers (Java)
- Add Two Numbers LeetCode Java
- 【Leetcode】Add two numbers JAVA
- Leetcode Java Add Two Numbers
- Java Leetcode Add Two Numbers
- [LeetCode][Java] Add Two Numbers
- LeetCode : Add Two Numbers [java]
- leetcode:Add Two Numbers 【Java】
- Java-LeetCode-Add Two Numbers
- Add Two Numbers LeetCode Java
- [LeetCode]Add Two Numbers(Java)
- 【leetcode】Add Two Numbers-----Java
- leetcode Add Two Numbers(Java)
- Add Two Numbers leetcode java
- Leetcode – Add Two Numbers (Java)
- [leetcode NO.3] Add Two Numbers (JAVA)
- leetcode 第二题Add Two Numbers java
- [LeetCode Java] 2 Add Two Numbers
- DNS 服务基本配置
- install mpich2 in rhel4
- 使用shell脚本删除当前目录下.c文件对应的可执行文件
- vmware installtion and configuration for linux
- Linux驱动开发必看详解神秘内核(完全转载)
- LeetCode : Add Two Numbers [java]
- 把数组排成最小的数
- MTK TAB页面的实现
- MTK 09B 新特性学习
- 遍历文件,寻找错误信息
- Android学习网站,资料推荐,学习经验共享
- 生成修改记录
- 内核学习入门
- MTK 10A 新特性学习