前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Add Two Numbers

Add Two Numbers

作者头像
青木
发布2018-05-28 15:16:40
5830
发布2018-05-28 15:16:40
举报

Problem

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8

解题思路

就是按照我们小时候的竖式加法的方式来计算就可以了。不同的是,这里的进位是向右进位;而我们小时候计算加法的进位是向左进位。

My Solution

代码语言:javascript
复制
class Solution
{
public:
	ListNode* addTwoNumbers(ListNode *l1, ListNode *l2)
	{
		ListNode* p = l1;
		ListNode* q = l2;
		int sum = 0;
		ListNode* sentinel = new ListNode(0);
		ListNode* d = sentinel;
		if ((p == NULL) && (q != NULL))
		{
			return q;
		}
		if ((p != NULL) && (q == NULL))
		{
			return p;
		}
		do
		{
			if (p != NULL)
			{
				sum += (p->val);
				p = p->next;
			}
			else
            {
				sum += 0;
               // p = p->next;
			}

			if (q != NULL)
			{
				sum += (q->val);
				q = q->next;
			}
			else
			{
				sum += 0;
              //  q = q->next;
			}
			d->next = new ListNode((sum % 10));
            d = d->next;
			sum = (sum/10);
            if(q==NULL && q==NULL && sum!=0)
            {
                d->next=new ListNode(sum);
            }
		}while (p != NULL || q != NULL);
		return sentinel->next;
	}

};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Problem
  • Example
  • 解题思路
  • My Solution
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档