LeetCode 2, Add Two Numbers
来源:互联网 发布:西门子s7200软件下载 编辑:程序博客网 时间:2024/06/16 08:41
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
/** * 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* l=l1; ListNode* m=l2; int a=0; if(l1==NULL) return l2; else if(l2==NULL) return l1; else{ while(l1->next!=NULL&&l2->next!=NULL) { a+=l1->val+l2->val; if(a>9) { l1->val=a%10; l2->val=a%10; a=1; } else { l1->val=a; l2->val=a; a=0; } l1=l1->next; l2=l2->next; } if(l1->next==NULL&&l2->next==NULL) { if(l1->val+l2->val+a>9) { l1->val=(l1->val+l2->val+a)%10; l1->next=new ListNode(1); } else l1->val=l1->val+l2->val+a; return l; } else if(l1->next==NULL) { if(l1->val+l2->val+a>9) { l2->val=(l1->val+l2->val+a)%10; while(l2->next!=NULL) { l2=l2->next; if(l2->val==9) l2->val=0; else { l2->val+=1; break; } } if(l2->next==NULL&&l2->val==0) { l2->next=new ListNode(1); } } else l2->val+=l1->val+a; return m; } else { if(l1->val+l2->val+a>9) { l1->val=(l1->val+l2->val+a)%10; while(l1->next!=NULL) { l1=l1->next; if(l1->val==9) l1->val=0; else { l1->val+=1; break; } } if(l1->next==NULL&&l1->val==0) { l1->next=new ListNode(1); } } else l1->val+=l2->val+a; return l; } } }};
0 0
- LeetCode 2 - Add Two Numbers
- LeetCode 2: Add Two Numbers
- Leetcode: Add Two Numbers (2)
- [leetcode 2] Add Two Numbers
- [Leetcode] 2 - Add Two Numbers
- LeetCode 2:《Add Two Numbers》
- LeetCode | #2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- [Leetcode]2Add Two Numbers
- leetcode #2 Add Two Numbers
- leetcode-2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- [leetcode] #2 Add Two Numbers
- LeetCode-2 Add Two Numbers
- LeetCode-2-Add Two Numbers
- Leetcode[2] Add Two Numbers
- LeetCode 2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- leetcode笔记—二进制数中1的个数
- zoj5093Battle ships【二分图 棋盘覆盖有断点】
- Oracle EBS登陆后,直接打开某个特定Form或Page
- leetcode-26. Remove Duplicates from Sorted Array
- Android学习记录(五) 记录一下最近遇到的坑:android actionbar menu菜单无显示。
- LeetCode 2, Add Two Numbers
- 文件过滤<FilenameFilter>
- 2016面试爬坑之我所遇到的面试题(不定时更新,答案仅供参考)
- 软件工程(摘抄)
- 张庭宾的博客
- UVa 12657 Boxes in a Line 数组模拟双向循环链表
- hdu 3342 Legal or Not 拓扑排序
- Linux进程管理-调度-通信-
- Linux的chattr与lsattr命令详解