2. Add Two Numbers
来源:互联网 发布:淘宝抽奖转盘怎么弄 编辑:程序博客网 时间:2024/06/06 20:55
题目
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 ->
想法
定义一个进位变量,创建一个链表。 仿照数学中对两个整数的相加,将和放在新建的链表里。
代码struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode * sum = malloc( sizeof( struct ListNode ) ), *coSum = sum; int carry = 0; while( 1 ) { coSum->val = ( l1 ? 0 : l1->val ) + ( l2 ? 0 : l2->val ) + carry; l1 = l1 ? NULL : l1->next; l2 = l2 ? NULL : l2->next; carry = coSum->val / 10; coSum->val %= 10; if( l1 || l2 || carry != 0 ) { coSum->next = malloc( sizeof( struct ListNode ) ); coSum = coSum->next; } else { coSum->next = NULL; return sum; } } }
0 0
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 2.Add Two Numbers
- 2. Add Two Numbers
- 2. Add Two Numbers
- 历届试题 买不到的数目
- eclipse with android : Didn't find class "com.xx.xx.MainActivity" on path: DexPathList
- hadoop安全模式
- 算法回望——归并排序
- js html代码转译防xss攻击
- 2. Add Two Numbers
- jsp的9大内置对象
- 初试turtle绘图库
- 使用u-boot的tftp下载功能烧写程序到Nand Flash ——韦东山嵌入式Linux学习笔记09
- 信号频率和带宽的关系
- gcc 编译选项宏定义
- C++ Primer 第5版--练习10.29
- js select下拉框的值
- mysql 5