Leetcode add-two-numbers
来源:互联网 发布:极客大数据 编辑:程序博客网 时间:2024/06/05 00:36
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 *h1=l1,*h2=l2; bool ok=true; while(h1&&h2){ h1=h1->next; h2=h2->next; } if(h2){ h1=l2; h2=l1; ok=false; } else{ h1=l1; h2=l2; } if(h1){ int flag=0; while(h2){ h1->val+=h2->val+flag; flag=0;//要及时把进位标志清0 if(h1->val>=10){ flag=1; h1->val%=10; } h2=h2->next; h1=h1->next; } while(h1){ h1->val+=flag; flag=0; if(h1->val>=10){ flag=1; h1->val%=10; } h1=h1->next; } if(flag){//首位有进位 if(ok){ h1=l1; } else{ h1=l2; } while(h1->next){ h1=h1->next; } ListNode *p=new ListNode(flag); p->next=h1->next; h1->next=p; } } return ok?l1:l2; }};
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
- storm入门
- Java千百问_06数据结构(024)_用二进制如何表示整型数值
- SCPPO(六):源代码管理工具---Team Foundation Server
- HDU 1846 Brave Game(博弈)
- 欢迎使用CSDN-markdown编辑器
- Leetcode add-two-numbers
- NASA 美国国家航空航天局开源项目列表
- SSH安装
- Intel Edison开机自动加载Arduino代码
- hdu 5067 Harry And Dig Machine (TSP类,简单)
- 1095. Cars on Campus (30)
- Python 也能干大事 —— 解方程
- git命令cherrypick
- 189. Rotate Array