[LeetCode] Add Two Numbers problem solving report (Java), leetcodenumbers
[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
[Description]
This question is not difficult, and the idea is intuitive and basic skills are tested.
It is required to traverse two linked lists. Note that if the last node has a forward position, a new node is required.
A lot of code on the Internet is to create a new linked list to store the results. I think l1 can be used directly to store the results.
A lot of code on the Internet looks shorter, but the time complexity is not reduced. For ease of understanding, I think it is clearer to write it below.
[Java code]
/*** 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) {if (l1 = null) return l2; if (l2 = null) return l1; // store the added result in the Linked List 1. pre1 is used for the ListNode ret = l1 next to the new node after the last bit; listNode pre1 = new ListNode (0); pre1.next = l1; int fla G = 0; while (l1! = Null & l2! = Null) {l1.val = l1.val + l2.val + flag; flag = l1.val/10; l1.val = l1.val % 10; pre1 = l1; l1 = l1.next; l2 = l2.next ;} // if linked list 2 is left, it is connected to if (l2! = Null) {pre1.next = l2; l1 = l2;} while (l1! = Null) {l1.val + = flag; flag = l1.val/10; l1.val = l1.val % 10; pre1 = l1; l1 = l1.next;} if (flag> 0) {ListNode node = new ListNode (1); pre1.next = node;} return ret ;}}
Add two numbers to 19 and make it less than 20How can it be?
Because x + y + 19 <20 SO x + y <1 SO x <1-y
Java native (JNI) question!
Use System. loadLibrary to add dll to System path at the same time
Although this method is clumsy
But the problem should be solved.