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

    Description:

    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.

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

    • Difficulty: Medium

    简单解释一下题意,两个位置颠倒(例如:892写成298)的数字相加后,按正常顺序输出结果。

    解题思路:

    1.从左到右开始互加计算,倘若在某位相加和大于等于10,要向右一位加1,而不是左一位加1.

    2.题目要求返回的是链表,所以每进位得到的结果可以通过头插法插入到链表首位,最后得到题目要求的正常顺序的结果

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
              ListNode* head = new ListNode(0);
              ListNode* res = head;
              int tmp = 0;
              while(l1||l2||res){
                 int num = (l1? l1->val:0) + (l2? l2->val:0) + tmp;
                 tmp = num / 10;
                 res->next = new ListNode(num % 10);
                 res = res->next;
                 if(l1) l1 = l1->next;
                 if(l2) l2 = l2->next;
              }
              return head->next;

    }

  • 相关阅读:
    MFC中ON_COMMAND,ON_MESSAGE,ON_NOTIFY的区别
    BIOS和CMOS的区别
    强大工具psexec工具用法简介
    Win10如何搭建FTP服务器以实现快速传输文件
    WPA-PSK无线网络破解原理及过程
    Wifi密码破解实战
    洋流.地球:四季只剩下冬天吗?
    天文.地球:最多的陨石有多大?
    德芙背后刻骨铭心的痛
    TTS
  • 原文地址:https://www.cnblogs.com/sarahp/p/6456085.html
Copyright © 2011-2022 走看看