【LeetCode算法练习(C语言)】Add Two Numbers
来源:互联网 发布:ibatis 打印sql语句 编辑:程序博客网 时间:2024/06/06 17:52
题目:
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
链接:Add Two Numbers
解法:大数加法,时间O(n)
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode *p = (struct ListNode *)malloc(sizeof(struct ListNode)); p->val = 0; p->next = NULL; int add = 0; struct ListNode *pp = p; while (l1 && l2) { if (l1->val + l2->val + add < 10) { pp->val = l1->val + l2->val + add; add = 0; } else { pp->val = l1->val + l2->val + add - 10; add = 1; } struct ListNode *t = (struct ListNode *)malloc(sizeof(struct ListNode)); t->val = 0; t->next = NULL; pp->next = t; pp = t; l1 = l1->next; l2 = l2->next; } while (l1) { if (l1->val + add < 10) { pp->val = l1->val + add; add = 0; } else { pp->val = l1->val + add - 10; add = 1; } struct ListNode *t = (struct ListNode *)malloc(sizeof(struct ListNode)); t->val = 0; t->next = NULL; pp->next = t; pp = t; l1 = l1->next; } while (l2) { if (l2->val + add < 10) { pp->val = l2->val + add; add = 0; } else { pp->val = l2->val + add - 10; add = 1; } struct ListNode *t = (struct ListNode *)malloc(sizeof(struct ListNode)); t->val = 0; t->next = NULL; pp->next = t; pp = t; l2 = l2->next; } if (add) { pp->val = 1; } else { struct ListNode *tmp = p; while (tmp->next != pp) { tmp = tmp->next; } tmp->next = NULL; free(pp); } return p;}
Runtime: 45 ms
阅读全文
0 0
- 【LeetCode算法练习(C语言)】Add Two Numbers
- [C语言][LeetCode][2]Add Two Numbers
- leetcode 2:Add Two Numbers(C语言)
- 【LeetCode】2. Add Two Numbers C语言
- Leetcode c语言-Add Two Numbers
- 【LeetCode编程学习(C语言)】2.Add Two Numbers
- 算法练习(1):Add Two Numbers
- leetcode练习 Add Two Numbers
- 算法练习:Add Two Numbers
- 【leetcode 2】 Add Two Numbers(C++)
- LeetCode 2. Add Two Numbers(C++)
- [LeetCode] Add Two Numbers(C++)
- leetcode 2. Add Two Numbers C语言实现
- 【LeetCode】 445. Add Two Numbers II C语言
- leetcode 练习——add two numbers (Java)
- [编程练习][Add Two Numbers]<LeetCode-2>
- 【LeetCode算法练习(C语言)】Two Sum
- 【LeetCode】Add Two Numbers Go语言实现
- 微信浏览器取消缓存的方法
- 静态库和动态库的制作(OC、Swift)
- 关于support-annotations库中的注解RequiresApi和Google官方文档
- 大量 D3.js 示例
- 数据库:索引
- 【LeetCode算法练习(C语言)】Add Two Numbers
- 【SQL Server学习笔记】6:更新/删除/导出/导入数据
- 使用moment.js轻松管理日期和时间
- HDU 1698 Just a Hook(线段树:区间更新,区间查询)
- 可变参数
- LinkedHashMap及其源码分析
- 1007.Numerical Summation of a Series
- Cookie和Session的区别
- 步态识别问题简介