Add Two Numbers

来源:互联网 发布:删除关联表数据 编辑:程序博客网 时间:2024/06/04 18:29

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

Have you been asked this question in an interview? 

cc上题目,注意如果让程序简练一些。
1 注意进位操作
2 注意 例如两个三位数想加,最后得到一个四位数。 即 最后再判断一下 carry 是否为0
3 如意如果两个链表长度不同的状况

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        ListNode dummy = new ListNode(- 1);        ListNode pre = dummy;        int carry = 0;        while (l1 != null && l2 != null) {            int value = (l1.val + l2.val + carry);            carry = value / 10;            value = value % 10;            pre.next = new ListNode(value);            pre = pre.next;            l1 = l1.next;            l2 = l2.next;        }         while (l2 != null) {                int value = (l2.val + carry);                carry = value / 10;                value = value % 10;                pre.next = new ListNode(value);                l2 = l2.next;                pre = pre.next;        }        while (l1 != null) {                int value = (l1.val + carry);                 carry = value / 10;                 value = value % 10;                 pre.next = new ListNode(value);                 l1 = l1.next;                 pre = pre.next;        }        if (carry != 0) {            pre.next = new ListNode(carry);        }        return dummy.next;    }}


0 0
原创粉丝点击