第二题怎么二次函数解答题

成长养成类(2)
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 {
ListNode(int x) { val = }
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null)
return null;
ListNode l = new ListNode(0);
int flag=0;
while(l1!=null || l2!=null)
ListNode lnext = new ListNode(0);
int a = l1==null?0:l1.
int b = l2==null?0:l2.
lnext.val = (a+b+flag)%10;
flag = (a+b+flag)/10;
l1 = l1==null?null:l1.
l2 = l2==null?null:l2.
if(flag != 0)
ListNode lnext = new ListNode(0);
lnext.val =
return lhead.
该解题思维相对正常,是靠生活计算经验解题,没有复杂算法,排名居中。
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:620次
排名:千里之外

我要回帖

更多关于 二元一次方程的解答题 的文章

 

随机推荐