leetcode-Add Tow Numbers

来源:互联网 发布:linux解包boot.img 编辑:程序博客网 时间:2024/06/08 05:13

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

思路:链表虽然是反置的,但是进位的方向是正确的,随意两个链表都从头遍历,进行就算就可以。计算中遇到一个链表为空时,其值置为0,只有当两个链表都为空时,才终止计算

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */
class Solution {     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        if(l1 == null)            return l2;        if(l2 == null)            return l1;        ListNode ansList = new ListNode(0), head = ansList;        int flag = 0;        while(true){            if(l1 == null && l2 == null){                if(flag == 1){                    ansList.next = new ListNode(flag);                }                break;            }            int add1 = l1==null ? 0:l1.val;            int add2 = l2==null ? 0:l2.val;            int sum = add1+add2+flag;            flag = sum/10;            ListNode node = new ListNode(sum%10);            ansList.next = node;            ansList = node;            if(l1 != null){                l1 = l1.next;            }            if(l2 != null){                l2 = l2.next;            }        }        return head.next;    }}
原创粉丝点击