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

    没啥好说的,类似与merge list的过程。对余下的list的操作可以合并,使代码看起来简洁。就是那个意思,体会一下。。。

     1     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
     2         ListNode A = l1;
     3         ListNode B = l2;
     4         int carry = 0;
     5         ListNode newHead = new ListNode(0);
     6         ListNode cur = newHead;
     7         while(A != null || B != null){
     8             if (A != null){
     9                 carry += A.val;
    10                 A = A.next;
    11             }
    12             if (B != null){
    13                 carry += B.val;
    14                 B = B.next;
    15             }
    16             cur.next = new ListNode(carry % 10);
    17             cur = cur.next;
    18             carry /= 10;
    19         }
    20         if (carry == 1) {
    21             cur.next = new ListNode(1);
    22         }
    23         return newHead.next;
    24     }
  • 相关阅读:
    RSA使用
    C#获取主机信息
    NSIS打包软件使用
    C#获取局域网主机
    C#实现Web链接启动应用程序
    4.布局介绍
    Server Sql 多表查询、子查询和分页
    C# File类常用方法
    Vue 使用技巧手记
    前端面试题手记
  • 原文地址:https://www.cnblogs.com/gonuts/p/4406564.html
Copyright © 2011-2022 走看看