首页 > 代码库 > Add Two Numbers
Add Two Numbers
https://oj.leetcode.com/problems/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
下面是一个不能处理超长数据的答案。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode node = l1; int l1Value = http://www.mamicode.com/0; int count = 0; while(node != null){ l1Value = l1Value + node.val * ((Double)Math.pow(10, count)).intValue(); count ++; node = node.next; } node = l2; int l2Value = http://www.mamicode.com/0; count = 0; while(node != null){ l2Value = l2Value + node.val * ((Double)Math.pow(10, count)).intValue(); count++; node = node.next; } int sumValue = http://www.mamicode.com/l1Value + l2Value; //int digits = (Math.floor((Double)(Math.log(sumValue) / Math.log(10) + 1)).intValue()); int digits = String.valueOf(sumValue).length(); if(sumValue < 10){ digits = 1; } ListNode[] listNodes = new ListNode[digits]; listNodes[0] = new ListNode(sumValue % 10); sumValue = sumValue / 10; for(int i = 1; i < digits; i++){ listNodes[i] = new ListNode(sumValue % 10); listNodes[i - 1].next = listNodes[i]; sumValue = sumValue / 10; } return listNodes[0]; }}
下面是一个AC的方法。技巧是,对于为null的node,全部置为0,再运算。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode node1 = l1; ListNode node2 = l2; ListNode node_current = new ListNode(0); ListNode node_next = node_current; ListNode node_return = node_current; while(node1 != null || node2 != null){ if(node1 == null){ node1 = new ListNode(0); } if(node2 == null){ node2 = new ListNode(0); } int sum = node1.val + node2.val + node_current.val; node_current.val = (node1.val + node2.val + node_current.val) % 10; if(sum > 9 || node1.next != null || node2.next !=null){ node_next = new ListNode(sum / 10); node_current.next = node_next; } node_current = node_next; if(node1 != null){ node1 = node1.next; } if(node2 != null){ node2 = node2.next; } } return node_return; }}
Add Two Numbers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。