2.Add Two Numbers——LeetCode

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.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

题目大意

逆序的链表从低位进行相加,得出的结果也逆序输出,返回值是逆序结果链表的头结点。

解题思路

注意进位问题

Input: (9 -> 9 -> 9 -> 9 -> 9) + (1 -> )
Output: 0 -> 0 -> 0 -> 0 -> 0 -> 1

这里引入一个变量carry当做进制位。我们把两个链表每一个对应位置的节点进行相加,如果长度不同,那么短的链表后面就是0,如123的逆序就是3210以此类推。

当然不能忽略的就是如果循环结束,进制位不为0的话,还要新增加一个节点,把carry放进去。

代码:

/**
 * Definition for singly-linked list.

 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int n1 = l1 != null ? l1.val : 0;   //当长度不等的时候短链表的节点值设为0
            int n2 = l2 != null ? l2.val : 0;
            /**
             * 完整写法
            int n1,n2;
            if (l1 != null)
                n1 = l1.val;
            else
                n1 = 0;

            if (l2 != null)
                n2 = l2.val;
            else
                n2 = 0;
             **/
            int sum = n1 + n2 + carry;
            if (head == null) {
                head = tail = new ListNode(sum % 10);
            } else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            carry = sum / 10;   //进制位向下取整
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry > 0) {    //如果循环结束,进制位不为0的话,还要新增加一个节点,把carry放进去
            tail.next = new ListNode(carry);
        }
        return head;
    }
}

Original: https://www.cnblogs.com/ancientlian/p/14294446.html
Author: Lian_tiam
Title: 2.Add Two Numbers——LeetCode

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/642634/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球