Problem
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1"s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
ExampleGiven 7->1->6 + 5->9->2. That is, 617 + 295.
Return 2->1->9. That is 912.
Given 3->1->5 and 5->9->2, return 8->0->8.
Note[null]
Solution/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; ListNode dummy = new ListNode(0); ListNode head = dummy; int carry = 0; while (l1 != null || l2 != null) { int sum = carry; if (l1 != null) { sum += l1.val; l1 = l1.next; } if (l2 != null) { sum += l2.val; l2 = l2.next; } carry = sum/10; head.next = new ListNode(sum%10); head = head.next; } if (carry != 0) head.next = new ListNode(carry); return dummy.next; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/65688.html
摘要:就不说了,使用的解法思路如下建立,对应该元素的值与之差,对应该元素的。然后,循环,对每个元素计算该值与之差,放入里,。如果中包含等于该元素值的值,那么说明这个元素正是中包含的对应的差值。返回二元数组,即为两个所求加数的序列。 Problem Given an array of integers, find two numbers such that they add up to a s...
Subsets Problem Given a set of distinct integers, return all possible subsets. Notice Elements in a subset must be in non-descending order.The solution set must not contain duplicate subsets. Example ...
摘要:去掉最后一个保留最后一个保留最后一个保留第一个这道题在论坛里参考了和两位仁兄的解法。思想是将中所有的数进行异或运算。不同的两个数异或的结果,一定至少有一位为。最后,将和存入数组,返回。 Problem Given 2*n + 2 numbers, every numbers occurs twice except two, find them. Example Given [1,2,2...
摘要:题目为求从到的自然数里取个数的所有组合全集。使用递归的模板,建立函数。模板如下也可以不建立新的,而是递归调用之后删去中最后一个元素 Problem Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. Example For example,If n = 4 a...
摘要:建立两个堆,一个堆就是本身,也就是一个最小堆另一个要写一个,使之成为一个最大堆。我们把遍历过的数组元素对半分到两个堆里,更大的数放在最小堆,较小的数放在最大堆。同时,确保最大堆的比最小堆大,才能从最大堆的顶端返回。 Problem Numbers keep coming, return the median of numbers at every time a new number a...
阅读 2958·2021-11-16 11:42
阅读 3619·2021-09-08 09:36
阅读 904·2019-08-30 12:52
阅读 2467·2019-08-29 14:12
阅读 723·2019-08-29 13:53
阅读 3562·2019-08-29 12:16
阅读 627·2019-08-29 12:12
阅读 2452·2019-08-29 11:16