leetcode--Add Two Numbers
来源:互联网 发布:arch linux chroot 编辑:程序博客网 时间:2024/06/04 19:53
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题目简单,没什么值得优化的
AC代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode*result=NULL; ListNode*lt1=l1; ListNode*lt2=l2; ListNode*tmp,*curr; int carry=0; int num; result=(ListNode*)malloc(sizeof(ListNode)); result->next=NULL; //result->val=9999; curr=result; while(lt1!=NULL&<2!=NULL){ if((num=lt1->val+lt2->val+carry)>9){ carry=1; num%=10; }else{ carry=0; } tmp=(ListNode*)malloc(sizeof(ListNode)); tmp->val=num; tmp->next=NULL; curr->next=tmp; curr=tmp; lt1=lt1->next; lt2=lt2->next; } if(lt1!=NULL){ while(lt1!=NULL){ if((num=lt1->val+carry)>9){ carry=1; num%=10; }else{ carry=0; } tmp=(ListNode*)malloc(sizeof(ListNode)); tmp->val=num; tmp->next=NULL; curr->next=tmp; curr=tmp; lt1=lt1->next; } } if(lt2!=NULL){ while(lt2!=NULL){ if((num=lt2->val+carry)>9){ carry=1; num%=10; }else{ carry=0; } tmp=(ListNode*)malloc(sizeof(ListNode)); tmp->val=num; tmp->next=NULL; curr->next=tmp; curr=tmp; lt2=lt2->next; } } if(carry==1){ tmp=(ListNode*)malloc(sizeof(ListNode)); tmp->val=1; tmp->next=NULL; curr->next=tmp; curr=tmp; } return result->next; }};
0 0
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- Leetcode : Add Two Numbers
- 【leetcode】Add Two Numbers
- [LeetCode]Add Two Numbers
- leetcode Add Two Numbers
- LeetCode-Add Two Numbers
- [leetcode] Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode - Add Two Numbers
- LeetCode | Add Two Numbers
- 【leetcode】Add Two Numbers
- HTTP返回码中301与302的区别
- Android调用webservice接收json
- 在xcode6.1和ios10.10.1环境下实现app发布
- 手机号,邮箱,车牌号合法性验证(手机号如果要支持更多的运营商的号码,比如177,要改一下正则表达式)
- 涉足计算机视觉领域要知道的
- leetcode--Add Two Numbers
- ios的webView加载本地html图片路径显示及webview适配
- surfaceview播放视频截图黑屏
- 互联网行业2015校园招聘
- 每个程序员需掌握的20个代码命名小贴士
- 程序员笑话
- NYOJ 2 括号配对问题(数据结构)
- 基于nginx搭建phpmyadmin环境
- 用Maven插件生成Mybatis代码