• 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

     主要是考虑进位

    Subscribe to see which companies asked this question

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    /*
     * 1.设置进位为0,并判断列表是否为空
     * 2.两个列表都不为空时,遍历,判断两个列表对应的值相加后是否大于10,大于就设置进位为1,否则为0
     * 3.一个列表为空的时候,进位+列表的对应的值,然后将剩下的添加到结果列表的尾部.
    * 4.两个列表都为空,进位位1,也添加
    */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if (NULL == l1 && NULL == l2) { return NULL; } else if (NULL == l1) { return l2; } else if (NULL == l2) { return l1; } ListNode* p1 = l1; ListNode* p2 = l2; ListNode* res_head = NULL; ListNode* res_index = NULL; int flag = 0; while (p1 != NULL && p2 != NULL) { int sum = p1->val + p2->val + flag; if (sum >= 10) { sum -= 10; flag = 1; } else { flag = 0; } ListNode* res_node = new ListNode(sum); if (NULL == res_head) { res_head = res_node; res_index = res_head; } else { res_index->next = res_node; res_index = res_node; } p1 = p1->next; p2 = p2->next; } while (p1 != NULL) { int sum = p1->val + flag; if (sum >= 10) { sum -= 10; flag = 1; } else { flag = 0; } ListNode* res_node = new ListNode(sum); res_index->next = res_node; res_index = res_node; p1 = p1->next; } while (p2 != NULL) { int sum = p2->val + flag; if (sum >= 10) { sum -= 10; flag = 1; } else { flag = 0; } ListNode* res_node = new ListNode(sum); res_index->next = res_node; res_index = res_node; p2 = p2->next; } if (0 != flag) { ListNode* res_node = new ListNode(flag); res_index->next = res_node; res_index = res_node; } return res_head; } };
  • 相关阅读:
    1553: Good subsequence (很奇妙的set模拟题,也可以直接暴力)
    1550: Simple String (做得少的思维题,两个字符串能否组成另外一个字符串问题)
    1549: Navigition Problem (几何计算+模拟 细节较多)
    1548: Design road (思维题 做法:三分找极值)
    Python 正则表达式入门(初级篇)
    Python中的正则表达式教程
    软件自动化测试的学习步骤
    自动化测试的Selenium的python版安装与使用
    自动化测试一些问题
    自动化测试
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5090387.html
Copyright © 2020-2023  润新知