LeetCode 0、《两数相加》
一、给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807 -----------------------------------------------------------
1、定义一个链表
class LinkedListNode
{
public object Value;
public LinkedListNode Next;
public LinkedListNode()
{
this.Value = null;
this.Next = null;
}
public LinkedListNode(int value)
{
this.Value = value;
this.Next = null;
}
}
public static LinkedListNode AddTwoNumber(LinkedListNode n1, LinkedListNode n2)
{
LinkedListNode ret = new LinkedListNode();
LinkedListNode cur = ret;
int carry = 0;
int sum;
while (n1 != null || n2 != null)
{
sum = (n1 == null ? 0 : (int)n1.Value) + (n2 == null ? 0 : (int)n2.Value) + carry;
carry = sum / 10;
cur.Value = sum % 10;
if (n1 != null)
n1 = n1.Next;
if (n2 != null)
n2 = n2.Next;
cur.Next = new LinkedListNode();
cur = cur.Next;
}
if (carry == 1)
cur.Next = new LinkedListNode(1);
return ret;
}
调用
LinkedListNode n1 = new LinkedListNode(2);
n1.Next = new LinkedListNode(4);
n1.Next.Next= new LinkedListNode(3);
LinkedListNode n2 = new LinkedListNode(5);
n2.Next = new LinkedListNode(6);
n2.Next.Next = new LinkedListNode(8);
LinkedListNode nk = AddTwoNumber(n1, n2);
最新文章
- 2014优秀的好用的20款免费jQuery插件推荐
- java内存配置
- JAVA自定义事件监听完整例子---sunfruit[转]
- OPW-00001: Unable to open password-file
- 《Python 学习手册4th》 第四章 介绍Python对象类型
- leetcode first bad version python
- poj 1041 John's trip 欧拉回路
- jquery下php与ajax的互传数据(json格式)自我总结
- vr &; obv
- String的valueOf()用于将其它类型转换为字符串
- C# 利用位运算传递多个参数方法
- 常见Python脚本
- 【C++】如何接收函数return返回来的数组元素
- 2.ES6引进的新特性——类Class
- React 中的 Component、PureComponent、无状态组件 之间的比较
- vs2013 std::sort 分析
- River Hopscotch
- Mac OSX安装 GitLab 5.x
- UVA-10054 The Necklace (欧拉回路)
- C# 高德地图调用帮助类 GaodeHelper