LeetCode第二题 Add Two Sum 首先我们看题目要求: 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) + ...
Output: 7 -> 0 -> 8 思路:要考虑到进位,考虑到产生新的节点还有就是不同链的长短,都考虑进去就很好解决了。 1classSolution(object):2defaddTwoNumbers(self, l1, l2):3"""4:type l1: ListNode5:type l2: ListNode6:rtype: ListNode7"""8a =09head =ListNode(a)10q =head11flag =01213whilel1a...
1classSolution {2public:3ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {4ListNode *res =newListNode(-1);5ListNode *cur =res;6intcarry =0;7while(l1 ||l2) {8intn1 = l1 ? l1->val :0;9intn2 = l2 ? l2->val :0;10intsum = n1 + n2 +carry;11carry = sum /10;12cur->...
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. 你有两个非空链表,表示两个非负整数,数字以相反的顺序存储,每个节点中包...
EasyLeetCode 02,两数相加(Add Two Numbers) 作者| 梁唐 大家好,我是梁唐。 题意 题意很简单,给定两个非空的链表。用逆序的链表来表示一个整数,要求我们将这两个数相加,并且返回一个同样形式的链表。 除了数字0之外,这两个数都不会以0开头,也就是没有前导0。
代码实现-Java 01 解法一 由于加法需要从最低位开始运算,而最低位在链表末尾,链表只能从前往后遍历,没法取到前面的元素,那怎么办呢? 我们可以利用栈来保存所有的元素,然后利用栈的后进先出的特点就可以从后往前取数字了,我们首先遍历两个链表,将所有数字分别压入两个栈s1和s2中,我们建立一个值为0的head节点,然...
[Leetcode] Add Binary 二进制相加 Add Binary Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". 模拟加法 复杂度 时间O(N) 空间 O(1) 思路 模拟加法的运算法则,从最低位加到最高位。记得使用StringBuilder来减少字符串操作的开销...
class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { // Start typing your C/C++ solution below if(l1 == NULL && l2 == NULL) { return NULL; } ListNode *retList = new ListNode(0); ListNode *tmpList = retList; ...
总结:Java 位操作,返回仍是 int, 需要再次进行强制转换为byte。 ** Anyway, Good luck, Richardo! My code: public class Solution { public String addBinary(String a, String b) { if (a == null || a.length() == 0) return b; else if (b == null || b.length() == 0) ...
https://leetcode.com/problems/add-two-numbers-ii/discuss/239282/Iterative-O(N)-Time-O(1)-space-without-modifying-input-list-Java-solution 这是我leetcode论坛上的帖子。 这题不难,但是follow up比较苛刻。 follow up要求不能改变input list, 这样我们就不能reverse input list然后从低到高做。