zoukankan      html  css  js  c++  java
  • Add Two Numbers

    You are given two linked lists representing two non-negative numbers. 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.

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if (l1==null) {
                return l2;
            }
            if (l2==null) {
                return l1;
            }
            ListNode tail=null,p1=l1,p2=l2;
            //进位的数字
            int add = 0;
            ListNode head = null;
            while (p1!=null && p2!=null) {
                int sum = p1.val+p2.val+add;
                add = (sum)/10;
                if (tail==null) {
                    tail = new ListNode((sum)%10);
                    head = tail;
                } else {
                    tail.next = new ListNode((sum)%10);
                    tail = tail.next;
                }
                p1 = p1.next;
                p2 = p2.next;
            }
            while (p1!=null) {
                int sum = p1.val+add;
                add = (sum)/10;
                tail.next = new ListNode((sum)%10);
                tail = tail.next;
                p1 = p1.next;
            }
            while (p2!=null) {
                int sum = p2.val+add;
                add = (sum)/10;
                tail.next = new ListNode((sum)%10);
                tail = tail.next;
                p2 = p2.next;
            }
            //最后一位 如果还有进位,需要加一位
            if (add!=0) {
                tail.next = new ListNode(add);
            }
            return head;
        }
    }
  • 相关阅读:
    着手写windows下的c语言这本书。
    ASP.NET Web页生命周期和执行的方法
    Windows 控制面板调用命令
    C# 可指定并行度任务调度器
    .NET 实用扩展方法
    C# 读写锁
    WinForm中预览Office文件
    C#方法过滤器
    WinForm动态查询
    .NET ActiveMQ类库
  • 原文地址:https://www.cnblogs.com/23lalala/p/3506902.html
Copyright © 2011-2022 走看看