iOS Developer

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

2018-08-10  本文已影响229人  CC老师_HelloCoder

一.算法题

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.1 思路

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


Snip20180810_119.png

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.h>

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%10;
        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;
}

小编OS:

如有疑问,留言即可.胖C会利用空余时间给大家做一个简单解答的.
持续更新关注公众号!

image
上一篇 下一篇

猜你喜欢

热点阅读