Leetcode第二题解题java实现
来源:互联网 发布:图片制作软件app 编辑:程序博客网 时间:2024/05/16 23:52
问题:
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
审题:
该题把数字按位拆开以倒序方式存放在一个链表中,要求计算两个数字的和,以同样的方式返回。该题的考察点是链表的遍历,他以倒序存储数字,减低了解题的繁琐程度,想象一下,分别从两个链表中同时取出一个数,比如第一个,这两数都是个位上的数,直接相加即可,得到的数看是否有进位,把进位值记下。
我的想法是把两个链表的数挨个遍历取出,没取出一位数就相加再加进位,并对10求余,存到另外一个链表的节点中,取整得到进位,存起来,
一直循环到两链表为空。
解题:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1 == null && l2 == null) { return null; } ListNode lhead; ListNode l = new ListNode(0); lhead = l; int flag=0; while(l1!=null || l2!=null) { ListNode lnext = new ListNode(0); int a = l1==null?0:l1.val; int b = l2==null?0:l2.val; lnext.val = (a+b+flag)%10; flag = (a+b+flag)/10; l.next = lnext; l = l.next; l1 = l1==null?null:l1.next; l2 = l2==null?null:l2.next; } if(flag != 0) //如果还有进位,添加节点存入其中 { ListNode lnext = new ListNode(0); lnext.val = flag; l.next = lnext; } return lhead.next; }}
该解题思维相对正常,是靠生活计算经验解题,没有复杂算法,排名居中。
0 0
- Leetcode第二题解题java实现
- LeetCode题解 第二周
- Leetcode题解---Regular Expression Matching Java实现
- Leetcode题解---WildCard Matching Java实现
- LeetCode题解-java
- leetcode 第二题Add Two Numbers java
- 水题第二弹题解
- MS第二题解题思路
- leetcode 26题题解
- leetcode水题题解
- leetcode题--Java实现
- 第二题解
- LeetCode题解第二章线性表2.1.1~2.1.2
- leetcode 题解 自主实现atoi()函数
- LeetCode题解(Golang实现)--Add Two Numbers
- LeetCode题解(Golang实现)--Two Sum
- LeetCode题解(Golang实现)--Longest Palindromic Substring
- LeetCode第二题--实现两个数的和
- 如何将BCM4330的SDIO驱动改为SPI驱动
- java实现image和base64互转
- C++静态构造函数相关概念解析
- mapreduce实现矩阵相乘
- 讲java项目转成android项目
- Leetcode第二题解题java实现
- web上下文监听器ServletContextListener
- 办公用什么把txt转换成pdf
- “全员编程,广泛嵌入”(八)—— 智能工业装备
- 简单的基于YCrCb颜色空间的人脸检测(肤色)
- 关于P/Invoke(1)
- JSF之定时刷新
- 怎么转换word成pdf格式的文件
- 关于字符串翻转的一些事