• 2. Add Two Numbers


    2. Add Two Numbers

    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.
    

    解析:

    题目将存储在链表中的数据按照十进制数的方法相加,而且两个数字都是逆序存储的,也就是数字342的存储方式是 2 - > 4 - >3,如此我们就可以将这两个数字从第0个节点(低位,个位)开始相加,并将进位保存加给下一个高位之和。最后还要判断最高位的进位是否为1,如果为1就创建一个节点保存1即可。

    Solution:

    /**
     * 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 p1 = l1; // 为了不影响输入的参数链表创建一个临时的指针
            ListNode p2 = l2;
            ListNode dummy = new ListNode(0);// 创建一个结果的表头
            ListNode cur = dummy; // 结果的当前节点指针
            
            int sum = 0; // 两数之和
            while(p1 != null || p2 != null) { // 循环结束的条件:只要这两个链表任一个没到头就继续
                if(p1 != null) {
                    sum += p1.val;
                    p1 = p1.next;
                }        
                if(p2 != null) {
                    sum += p2.val;
                    p2 = p2.next;
                }
                cur.next = new ListNode(sum % 10);// 用结果创建一个节点
                cur = cur.next; // cur指针后移一个节点
                
                sum /= 10; // 获得进位
            }
            
            if(sum == 1) {
                cur.next = new ListNode(1);
            }
            
            return dummy.next;// 结果要求的是没有空的头节点的链表
        }
    }
    
  • 相关阅读:
    DOM 文本节点 、节点列表
    haslayout综合【转】
    css兼容性详解
    重温textjustify:interideograph
    掌握三点即可轻松打造出良好的交互设计效果
    ASP.NET 中的正则表达式
    Net中的反射使用入门
    ASP.NET2.0页面状态持续[转]
    使用XmlTextWriter对象创建XML文件[转]
    判断SQLSERVER数据库表字段为空的问题
  • 原文地址:https://www.cnblogs.com/zhuobo/p/10759058.html
Copyright © 2020-2023  润新知