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

本文共 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

你可能感兴趣的文章
发送邮件的工具类
查看>>
在asp.net中,添加itemtempert 项模板时,如果在项模板里有其它控件,如何控件这些控件的属性?...
查看>>
微软企业库5.0 学习之路——第八步、使用Configuration Setting模块等多种方式分类管理企业库配置信息...
查看>>
网络学习笔记:TCP/IP连网和Internet
查看>>
栈实现迷宫问题
查看>>
POJ2724 Purifying Machine(二分图)
查看>>
c++模板实现 linq
查看>>
spring security基本知识(三) 过滤详细说明
查看>>
python with语句上下文管理的两种实现方法
查看>>
谭永基来JNU Zhuhai开讲座了。
查看>>
HashMap和Hashtable的区别
查看>>
CCF NOI1067 最匹配的矩阵
查看>>
POJ3048 HDU2710 Max Factor
查看>>
KMP算法(C语言版)
查看>>
HDU 5726 GCD 求给定序列中与查询段相等的GCD个数
查看>>
docker基础总结
查看>>
Kafka~消费的有效期
查看>>
openSUSE Linux常用命令行记录
查看>>
JavaScript中如何判断两变量是否“相等”?
查看>>
算法练习(四)
查看>>