BAT面试算法进阶(1)--两数之和

2018-12-21  本文已影响0人  鉴皇师

一.算法题

题目

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.

输入: (2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 0 -> 8
原因: 342 + 465 = 807.
复制代码

二. 解决方案:

题目大意:给定2个非空链表来表示2个非负整数.位数按照逆序方式存储,它们的每个节点只存储单个数字,将两数相加返回一个新的链表.你可以假设除了数字0之外,这2个数字都不会以零开头.

2.1 思路

我们使用变量来跟踪进位,并从包含最低有效位的表头开始模拟逐位相加的过程.

<figure style="display: block; margin: 22px auto; text-align: center;">[图片上传失败...(image-2e1984-1545403878986)]

<figcaption style="display: block; text-align: center; font-size: 1rem; line-height: 1.6; color: rgb(144, 144, 144); margin-top: 2px;"></figcaption>

</figure>

2.2 算法

就如同小学数学计算2个数相加一般,我们首先从低位有效位计算,也就是L1,L2的表头第一个位置开始相加.我们进行的十进制相加,所以当计算的结果大于9时,就会造成"溢出"的现象.例如5+7=12.此时,我们就会把当前为的值设置为2,但是溢出的位需要进位.那么则用carry存储,carry = 1.带入到下一次迭代计算中.进位的carry必定是0或者1.2个数累加,需要考虑进位问题.则采用一个变量来保存进位值.

2.3 伪代码

2.4 复杂度分析

2.5 参考代码

#include <stdio>

struct ListNode {
    int val;
    struct ListNode *next;
};

struct ListNode* addTwoNumbers(struct ListNode * l1, struct ListNode *  l2) {

    struct ListNode *dummyHead = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode *p = l1, *q = l2, *curr = dummyHead;
    int carry = 0;
    while (p != NULL || q != NULL) {
        int x = (p != NULL) ? p->val : 0;
        int y = (q != NULL) ? q->val : 0;

        int sum = carry + x + y;
        carry = sum / 10;

        curr->next = (struct ListNode *)malloc(sizeof(struct ListNode));
        curr->val = sum;
        curr = curr->next;
        if (p != NULL) p = p->next;
        if (q != NULL) q = q->next;
    }
    if (carry > 0) {
        curr->next = (struct ListNode *)malloc(sizeof(struct ListNode));
    }

    return curr;
}
复制代码

感谢大家观看这一篇文章,给大家献上了iOS开发的188道面试题哦! 加小编的群就可以直接获取哦!551346706

Enter your image description here: Enter your image description here:
上一篇 下一篇

猜你喜欢

热点阅读