1、Algorithm
Add Two Numbers
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. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
要求:给到两个非空链表,它们表示两个非负整数。数字以相反的顺序存储它们的每个节点都包含一位数字。将这两个数字相加并以链表的形式返回。
编写代码:
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode firstNode = new ListNode(-1); ListNode resultNode = firstNode; int nextAddValue = 0, addValue = 0; if (l1 != null || l2 != null) { addValue = l1.val + l2.val; nextAddValue = addValue / 10; resultNode = new ListNode(addValue % 10); l1 = l1.next; l2 = l2.next; firstNode = resultNode; while (l1 != null || l2 != null || nextAddValue != 0) { addValue = nextAddValue; if (l1 != null){ addValue += l1.val; } if (l2 != null){ addValue += l2.val; } nextAddValue = addValue / 10; ListNode resNode = new ListNode(addValue % 10); resultNode.next = resNode; resultNode = resNode; if (l1 != null){ l1 = l1.next; } if (l2 != null){ l2 = l2.next; } } } return firstNode; } }
思路:循环,存在的情况,两个链表长度不一样,和的长度不一样。
2、Review
点评:文章列举了关于在面试的最后一个环节“问面试官问题”的5个最糟糕的问题,以及为什么作者会这么认为这些问题很糟糕。在阅读这篇文章的过程中,最大的感受是国外表述、说话的思路,理解起来感觉很吃力。比如:
But as for the worst questions? Oh yeah, that part is easy. And so, I give you my five least favorite questions to be asked in an interview, along with why I think they suck, and what you might ask instead.