【LeetCode】C# 2、Add Two Numbers

来源:互联网 发布:mac 网站编辑 编辑:程序博客网 时间:2024/06/10 15:04

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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

这个题目要考虑进位,考虑ListNode长度不等的问题,以及考虑ListNode长度走完之后还剩一个进位的情况。
所以我建了三个指针和新建一个result,先走完两个ListNode相加的部分,然后是单独的部分,最后加上进位。

public class Solution {    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {        ListNode one = l1, two = l2;        ListNode res = new ListNode(0);        ListNode three = res;        int sum=0;        while(one!=null && two!=null){            three.next = new ListNode((one.val+two.val+sum)%10);            sum=(one.val+two.val+sum)/10;            one=one.next;            two=two.next;            three=three.next;        }        while(one!=null){            three.next = new ListNode((one.val+sum)%10);            sum=(one.val+sum)/10;            one=one.next;            three=three.next;        }        while(two!=null){            three.next = new ListNode((two.val+sum)%10);            sum=(two.val+sum)/10;            two=two.next;            three=three.next;        }        if(sum!=0)            three.next = new ListNode(1);        return res.next;    }}
原创粉丝点击