Leetcode2. Add Two Numbers
来源:互联网 发布:淘宝收藏加购软件 编辑:程序博客网 时间:2024/06/06 00:42
题目:
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
思路:
没啥思路,就一位一位对应加就行,注意进位。
代码写得比较渣,但是好理解,也AC了。
import java.util.LinkedList;class ListNode { int val; ListNode next; ListNode(int x) { val = x; }}public class Test { public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { int carry = 0; LinkedList<Integer> list = new LinkedList(); while(l1 != null && l2 != null) { int a = l1.val; int b = l2.val; int result = a + b + carry; if(result >= 10) { result %= 10; carry = 1; }else { carry = 0; } list.add(result); l1 = l1.next; l2 = l2.next; } while(l1 != null) { int result = l1.val + carry; if(result >= 10) { result %= 10; carry = 1; }else { carry = 0; } list.add(result); l1 = l1.next; } while(l2 != null) { int result = l2.val + carry; if(result >= 10) { result %= 10; carry = 1; }else { carry = 0; } list.add(result); l2 = l2.next; } if(carry != 0) { list.add(carry); } // 创造返回链表 ListNode head = new ListNode(list.removeFirst()); ListNode result = head; while(!list.isEmpty()) { head.next = new ListNode(list.removeFirst()); head = head.next; } return result; } public static ListNode createTestCase(int[] arr) { ListNode head = new ListNode(-1); ListNode h = head; for(int i = 0; i < arr.length; i++) { head.next = new ListNode(arr[i]); head = head.next; } return h.next; } public static void print(ListNode head) { while(head != null) { System.out.print(head.val + " "); head = head.next; } System.out.println(); } public static void main(String[] args) { // Test case int[] arr1 = {2,4,5,1}; int[] arr2 = {5,6,4}; ListNode l1 = createTestCase(arr1); ListNode l2 = createTestCase(arr2); ListNode l3 = addTwoNumbers(l1, l2); print(l3); }}
阅读全文
0 0
- [LeetCode2]Add Two Numbers
- leetcode2 add two numbers
- LeetCode2 Add Two Numbers
- LeetCode2:Add Two Numbers
- LeetCode2 Add Two Numbers
- leetCode2:Add Two Numbers
- leetcode2--Add Two Numbers
- leetcode2 Add Two Numbers
- LeetCode2:Add Two Numbers
- leetcode2 Add Two Numbers
- Leetcode2 Add Two Numbers
- LeetCode2.Add Two Numbers
- Leetcode2: Add Two Numbers
- LeetCode2. Add Two Numbers
- LeetCode2. Add Two Numbers
- leetcode2. Add Two Numbers
- leetcode2~Add Two Numbers
- LeetCode2.Add Two Numbers
- Android的代码安全那些事
- 本地安装jekll环境
- hdoj 2028 Lowest Common Multiple Plus
- Spring Framework Overview
- Oracle触发器实现更新一张表数据时判断另一张表是否存在,存在更新数据,不存在插入数据
- Leetcode2. Add Two Numbers
- Servlet实现Cookie的创建,读取,删除
- SQL Server大量数据秒级插入/新增/删除
- 数据结构实验之栈与队列四:括号匹配
- oracle 11g 使用listagg函数合并多行为一行
- 分布式Paxos算法
- CSDN-markdown编辑器使用指南
- linux移植Mplayer基本配置与错误总结
- 别问为什么了 快上车 !!(axure 8.1注册码)