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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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...
閱讀 3014·2021-11-16 11:42
閱讀 3653·2021-09-08 09:36
閱讀 950·2019-08-30 12:52
閱讀 2481·2019-08-29 14:12
閱讀 769·2019-08-29 13:53
閱讀 3583·2019-08-29 12:16
閱讀 644·2019-08-29 12:12
閱讀 2469·2019-08-29 11:16