博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
2. Add Two Numbers
阅读量:6921 次
发布时间:2019-06-27

本文共 1969 字,大约阅读时间需要 6 分钟。

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.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8Explanation: 342 + 465 = 807.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {    struct ListNode* l = (struct ListNode*)malloc(sizeof(struct ListNode));    int last_sum = l1->val + l2->val,this_sum;    l->val = last_sum % 10;    struct listNode* head = l;    l1 = l1->next;    l2 = l2->next;    while(l1 && l2){        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));        this_sum = l1->val + l2->val;        node->val = (last_sum/10 + this_sum)%10;        last_sum = last_sum/10 + this_sum;        l->next = node;        l = node;        l1 = l1->next;        l2 = l2->next;    }    struct ListNode* l12 = (struct ListNode*)malloc(sizeof(struct ListNode));    l12 = NULL;    if(l1) l12 = l1;    if(l2) l12 = l2;    if(l12){        if(last_sum < 10){            l->next = l12;            return head;        }        else{            while(l12){                struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));                node->val = (last_sum/10 + l12->val)%10;                last_sum = last_sum/10 + l12->val;                l->next = node;                l = node;                l12 = l12->next;            }        }    }    if(last_sum/10){        struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));        node->val = last_sum/10;        l->next = node;        l = node;    }    l->next = NULL;    return head;}

转载于:https://www.cnblogs.com/JingwangLi/p/10202805.html

你可能感兴趣的文章
ClistCtrl列表控件添加复选框功能
查看>>
Storm 集群异常的解决
查看>>
7_12_2013 B: A simple problem
查看>>
linux常用命令less选项
查看>>
为什么php运行了 ignore_user_abort之后,前台网页访问不了呢。一直在加载
查看>>
ttylinux升级busybox脚本
查看>>
SEO 使用 robots.txt 文件拦截或删除网页
查看>>
Solr 删除索引
查看>>
rm -rf/ 又引发了一个血案
查看>>
我的友情链接
查看>>
docker 安装ElasticSearch(6.x版本)
查看>>
Confluence 6 MySQL 3.x 字符集编码问题
查看>>
HttpUtils
查看>>
HTML-特殊字符
查看>>
Android小白的探索:2D绘图之Android简易版Microsoft Visio学习之路 一、组合模式
查看>>
IBM PVM Study之--IBM PVM技术概述
查看>>
用组策略取消WINDOWS 2003 SERVER的关机原因
查看>>
activemq 使用介绍
查看>>
软件测试中有关界面测试经验总结-51testing
查看>>
34个高质量的扁平化设计资源
查看>>