LeetCode - Add Two Numbers
来源:互联网 发布:svd推荐算法 编辑:程序博客网 时间:2024/05/29 08:47
问题链接:https://oj.leetcode.com/problems/add-two-numbers/
问题描述:
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) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
问题API:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2)
分析:这题其实很简单,不知道为什么leetcode给的medium的难度。就是逐步往下加然后保留进位即可。代码如下:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1 == null || l2 == null) return l1 == null ? l2 : l1; ListNode tmp1 = l1, tmp2 = l2; int next = 0, curbit = 0; ListNode res = new ListNode(0); ListNode tmp = res; while(tmp1 != null || tmp2 != null || next != 0){ curbit = (tmp1 != null ? tmp1.val : 0) + (tmp2 != null ? tmp2.val : 0) + next; next = curbit / 10; tmp.val = curbit % 10; if(tmp1 != null) tmp1 = tmp1.next; if(tmp2 != null) tmp2 = tmp2.next; if(tmp1 != null || tmp2 != null || next != 0){ tmp.next = new ListNode(0); tmp = tmp.next; } } return res; }
这题其实有一个变种,难度骤然提升很多。
这题里面链表是按照个十百位逐步往下连接,如果链表的连接方式是按照正常从高往低
也就是 1 - > 2 - > 3表示的不是321而是123。用O(n)的方式做加法。
分析和代码随后放上。
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- Leetcode : Add Two Numbers
- 【leetcode】Add Two Numbers
- [LeetCode]Add Two Numbers
- leetcode Add Two Numbers
- LeetCode-Add Two Numbers
- [leetcode] Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode - Add Two Numbers
- LeetCode | Add Two Numbers
- 【leetcode】Add Two Numbers
- 如何配置服务器以侦听特定 TCP 端口(SQL Server 配置管理器)
- Android最佳性能实践(二)——分析内存的使用情况
- 第六章图知识导图
- 在Windows 64位操作系统安装Weblogic的注意事项
- MapReduce Design Patterns(chapter 1)(一)简介
- LeetCode - Add Two Numbers
- mysql字段内容部分截取
- linux内核导出符号
- 听雪
- X5开发工具 使用execl导入组件 导入数据后 对导入数据进行处理
- Python学习资料
- SharePoint 2013 日历重叠功能简介
- Spring 中的p标签
- 防火墙配置基础