leetcode 2---Add Two Numbers 进位 链表 数学

来源:互联网 发布:天猫双十一数据直播 编辑:程序博客网 时间:2024/06/04 19:49

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

解题思路:可以参考二进制数相加那个题,但是这个题目不同的地方是从左向右的,也就是进位向右移动(够奇葩),因此简单了,直接移位就行了,需要注意的是链表的结构和空指针。借助哑节点和双指针可以方便的解决问题,一个负责移位、一个负责存储。

/** * 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) {     ListNode pre=new ListNode(0);     ListNode head=pre;     int carry=0;     while(l1!=null||l2!=null||carry!=0){            ListNode curr=new ListNode(0);            int sum=(l1==null?0:l1.val)+(l2==null?0:l2.val)+carry;            carry=sum/10;            curr.val=sum%10;            pre.next=curr;//相当于存储,赋值            pre=curr;//移位            l1=(l1==null?null:l1.next);            l2=(l2==null?null:l2.next);        }        return head.next;    }}

如果题目换一下,进位是从右往左进行的,这个时候就得考虑链表的反转了。。。。

0 0
原创粉丝点击