String和number的未解锁的题先放一放,开始linked list.
Question
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contains 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
*Difficulty: Medium, Frequency: High
https://leetcode.com/problems/add-two-numbers/
My Solution
/**
* 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) {
ListNode dummyHead = new ListNode(0);
ListNode R = dummyHead;
int carryOn = 0;
while(l1 != null || l2 != null || carryOn == 1){
int l1v = (l1!=null) ? l1.val : 0 ;
int l2v = (l2!=null) ? l2.val : 0 ;
int sum = l1v + l2v + carryOn;
if(sum >= 10){
sum = sum - 10;
carryOn = 1;
}else carryOn = 0;
ListNode sumNode = new ListNode(sum);
R.next = sumNode;
if(l1!=null) l1 = l1.next;
if(l2!=null) l2 = l2.next;
R = R.next;
}
return dummyHead.next;
}
}
comments
carryOn 是两个data structure相加通常的edge cases e.g.【9,9,9】+【1】=【0,0,0,1】