美文网首页
leetcode-2.两数相加

leetcode-2.两数相加

作者: sleepforests | 来源:发表于2020-03-25 21:39 被阅读0次

    题目

    https://leetcode-cn.com/problems/add-two-numbers/description/

    代码

    /*
     * @lc app=leetcode.cn id=2 lang=java
     *
     * [2] 两数相加
     */
    
    // @lc code=start
    /**
     * 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) {
            ListNode p = new ListNode(-1);
            ListNode head = p;
            
            int add = 0;
            while (l1 != null && l2 != null) {
                int vv = l1.val + l2.val + add;
                if (vv >= 10) {
                    add = 1;
                    vv = vv - 10;
                } else {
                    add = 0;
                }
                ListNode newNode = new ListNode(vv);
                p.next = newNode;
                p = p.next;
                l1 = l1.next;
                l2 = l2.next;
            }
    
            ListNode temp = l1 != null ? l1 : l2;
            while (temp != null) {
                int vv = temp.val + add;
                if (vv >= 10) {
                    add = 1;
                    vv = vv - 10;
                } else {
                    add = 0;
                }
                ListNode newNode = new ListNode(vv);
                p.next = newNode;
                p = p.next;
                temp = temp.next;
            }
    
            if (add == 1) {
                ListNode newNode = new ListNode(1);
                p.next = newNode;
                p = p.next;
            }
            return head.next;
        }
    
    }
    // @lc code=end
    
    

    相关文章

      网友评论

          本文标题:leetcode-2.两数相加

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