博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 2. Add Two Numbers
阅读量:7212 次
发布时间:2019-06-29

本文共 1714 字,大约阅读时间需要 5 分钟。

2. Add Two Numbers

Question
Total Accepted: 123735 Total Submissions: 554195 Difficulty: Medium

 

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

 

 to see which companies asked this question

Hide Tags
 
 
Show Similar Problems
 
new 新的节点参考了:
 
核心代码:
1 ListNode *p = new ListNode(sum % 10);2

 

比较好的思路:

直接用了 取余 和 /10 操作,少一步判断 是否要进位。

 

1 /** 2  * Definition for singly-linked list. 3  * struct ListNode { 4  *     int val; 5  *     ListNode *next; 6  *     ListNode(int x) : val(x), next(NULL) {} 7  * }; 8  */ 9 class Solution {10 public:11     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {12         ListNode* tail = NULL;13         ListNode* head = NULL;14         int sum = 0;15         while(l1 != NULL || l2 != NULL){16             if(l1 != NULL){17                 sum += l1->val;18                 l1 = l1->next;19             }20             if(l2 != NULL){21                 sum += l2->val;22                 l2 = l2->next;23             }24             ListNode *p = new ListNode(sum % 10);25             if (head == NULL) {  26                 head = p;  27                 tail = p;  28             } else {  29                 tail->next = p;  30                 tail = p;  31             }  32             sum /= 10;33         }34         if(sum != 0){35             ListNode *p = new ListNode(sum % 10);36             tail->next = p;  37             tail = p;  38         }39         tail->next = NULL;40         return head;41     }42 };

 

转载于:https://www.cnblogs.com/njczy2010/p/5229958.html

你可能感兴趣的文章
基于zeromq的高性能分布式RPC框架Zerorpc 性能测试
查看>>
IL系列文章之二:Make Best Use of Our Tools
查看>>
Apache Ant使用过程的总结
查看>>
ES 相似度算法设置(续)
查看>>
oc73--NSArray使用
查看>>
Backbone.js入门学习资源
查看>>
类型转化:float -> DWORD
查看>>
Android自定义视图二:如何绘制内容
查看>>
Python天天美味(21) - httplib,smtplib
查看>>
第 37 章 ACOS - CLI
查看>>
Lock-Free 编程
查看>>
7.3. 查看命令
查看>>
解决Wamp 开启vhost localhost 提示 403 Forbbiden 的问题!
查看>>
[WinAPI] API 14 [获取、设置文件属性和时间]
查看>>
AutoCompleteTextView 和 TextWatcher 详解
查看>>
2.5. SciTE
查看>>
喵哈哈村的魔法考试 Round #1 (Div.2) 题解&源码(A.水+暴力,B.dp+栈)
查看>>
【转载】Java 内存分配全面浅析
查看>>
【Android】监听Notification被清除
查看>>
jQuery动态五星评分
查看>>