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 contains 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

    解答:

     1 public ListNode  addTwoNumbers(ListNode l1, ListNode l2) {
     2     ListNode dummyHead = new ListNode(0);
     3     ListNode p = l1;
     4     ListNode q = l2;
     5     ListNode curr = dummyHead;
     6 
     7     int carry = 0;
     8 
     9     while(p != null || q != null) {
    10         int x = (p != null)?p.val:0;
    11         int y = (q != null)?q.val:0;
    12 
    13         int digit = x + y + carry;
    14         carry = digit / 10;
    15         curr.next = new ListNode(digit % 10);
    16         curr = curr.next;
    17 
    18         if(p != null) {
    19             p = p.next;
    20         }
    21 
    22         if(q != null) {
    23             q = q.next;
    24         }
    25     }
    26 
    27     if(carry > 0) {
    28         curr.next = new ListNode(carry);
    29     }
    30 
    31     return dummyHead;
    32 }

  • 相关阅读:
    对象访问方式
    GC回收的对象
    邮件工具类
    java内存区域
    RabbitMQ的安装
    Flask信号
    DBUtils数据库连接池
    Flask蓝图基本使用
    Flask中使用cookie和session
    Flask中的CBV
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10412530.html
Copyright © 2011-2022 走看看