美文网首页
【LeetCode】2. Add Two Numbers

【LeetCode】2. Add Two Numbers

作者: 竞技等级几点叫你你呢 | 来源:发表于2017-08-13 22:19 被阅读0次

    原文: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本身。


    过程:

    总结:

    1 . 链表的add
    2 . 两个链表长度不同,空指针
    3 . 进位问题

    代码实现

    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if (null == l1) {
                return l2;
            }
            if (null == l2) {
                return l1;
            }
            ListNode result = new ListNode(0);
            int carry = 0;  //进位
            int sum = 0;
            while (l1 != null || l2 != null) {
                sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;  //求和
                carry = sum / 10;  //进位
                sum = sum % 10;    //值
                ListNode root = new ListNode(sum);  //初始化一个节点
    
                result = addListNode(result, root);
    
                l1 = l1 == null ? null : l1.next;
                l2 = l2 == null ? null : l2.next;
            }
            if (carry != 0) {
                ListNode root = new ListNode(1);  //初始化一个节点
                result = addListNode(result, root);
            }
            return result.next;
        }
    
        /**
         * add  节点
         *
         * @param result
         * @param root
         * @return
         */
        public ListNode addListNode(ListNode result, ListNode root) {
            if (result.next == null) {
                result.next = root;
                return result;
            }
            ListNode tmp = result.next;
            while (tmp.next != null) {
                tmp = tmp.next;
            }
            tmp.next = root;
            return result;
        }
    }
    

    ListNode类

    public class ListNode {
        int val;
        ListNode next;
    
        public ListNode(int x) {
            val = x;
        }
    }
    

    相关文章

      网友评论

          本文标题:【LeetCode】2. Add Two Numbers

          本文链接:https://www.haomeiwen.com/subject/gngerxtx.html