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

     题意,反向表达,相加之后还是以链表的形式表达。

     1 class Solution {
     2 public:
     3 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
     4 {
     5 int forw=0;//进位标志
     6 //建立一个新的链表存储答案
     7 ListNode root(0);
     8 ListNode *output=&root;
     9 while(l1||l2)
    10 {
    11 int v1 = (l1 ? l1->val : 0);
    12 int v2 = (l2 ? l2->val : 0);
    13 int sum=v1+v2+forw;
    14 //检验sum是否为两位数
    15 forw=sum/10;
    16 sum=sum%10;
    17 ListNode *coNode=new ListNode(sum);
    18 output->next=coNode;
    19 output=coNode;
    20 if(l1)l1=l1->next;
    21 if(l2)l2=l2->next;
    22 }
    23 if(forw>0)
    24 {
    25 ListNode *coNode=new ListNode(forw);
    26 output->next=coNode;
    27 output=coNode;
    28 }
    29 return root.next;
    30 }
    31 };

      

  • 相关阅读:
    【NOIP2017】奶酪
    【NOIP2017】时间复杂度
    【NOIP2005】过河
    【洛谷习题】垃圾陷阱
    dfs序
    bzoj2441 小W的问题
    彩色迷宫
    蛋糕与蛋挞
    树上倍增
    因数个数定理
  • 原文地址:https://www.cnblogs.com/bowiehsu/p/4122238.html
Copyright © 2011-2022 走看看