LeetCode——002
来源:互联网 发布:线切割3b编程软件 编辑:程序博客网 时间:2024/06/05 22:38
/*/////////////////////////////////////////////////////////////////////////////2. Add Two Numbers My Submissions QuestionEditorial SolutionTotal Accepted: 135842 Total Submissions: 594541 Difficulty: MediumYou 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 -> 8Subscribe to see which companies asked this question/////////////////////////////////////////////////////////////////////////////*//** * 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) { //如果有一条空,直接返回另一条就可以了,不需要再相加 if(l1==NULL)return l2; if(l2==NULL)return l1; ListNode* dummy=new ListNode(-1); ListNode* p=dummy; //进位变量 int carry=0; while(l1 || l2){ int a=l1==NULL ? 0: l1->val; int b=l2==NULL ? 0: l2->val; int tmp=a+b+carry; carry=tmp/10; ListNode* N=new ListNode(tmp%10); //链表指针后移 if(l1)l1=l1->next; if(l2)l2=l2->next; //结果链表指针后移 p->next=N; p=N; } //判断是否仍有进位 if(carry){ p->next=new ListNode(carry); p=p->next; } return dummy->next; }};
0 0
- LeetCode——002
- 开始刷刷Leetcode—leetcode第二题
- leetcode 002 —— add two numbers
- LeetCode —— Combinations
- LeetCode —— Triangle
- LeetCode —— Anagrams
- [leetcode] Subsets——@
- Permutations——LeetCode
- minimum_window_substring ——leetcode
- LeetCode——Candy
- LeetCode——Triangle
- LeetCode——Combinations
- LeetCode——Permutations
- *candy——leetcode
- gas_station——leetcode
- LeetCode——Candy
- LeetCode——Triangle
- LeetCode——Anagrams
- 错误:Failed to locate or generate matching signing assets
- 计算广告——搜索广告技术初窥
- 漫谈iOS RSA非对称加密与解密
- 登录成功后跳回到原来页面
- 新站优化前,研究关键词很关键
- LeetCode——002
- 捉急:ssh vim中不小心按下ctrl+s后卡死
- 王学岗屏幕适配(一)
- UIImage的各种处理(旋转,压缩,写入,读去,计算大小)等和方法的区别的介绍
- svg文本动态改变后字体设置丢失问题
- secure crt连接oracle 解决oracle账户锁定问题,并配置weblogic数据源
- Passwordless SSH Login
- PHP时间日期操作增减(date strtotime) 加一天 加一月
- LeetCode 13. Roman to Integer