namespace ApplicationCore.TestBase;
using System;
public class Class1
{
public static void Main(string[] args)
{
// 一个 node 代表一个数字,数字的大小理论上可以无限大
//[1,1,2,5] 321 node1
//[ 3,4,5] 543 node2
//[1,4,7,0] 864 result
var node1 = new Node()
{
Value = '1',
Next = new Node
{
Value = '1',
Next = new Node()
{
Value = '2',
Next = new Node()
{
Value = '5'
}
}
}
};
var node2 = new Node()
{
Value = '3',
Next = new Node()
{
Value = '4',
Next = new Node()
{
Value = '5'
}
}
};
Console.WriteLine(node1);
Console.WriteLine(node2);
var result = CombineNode(node1, node2);
Console.WriteLine(result);
Console.ReadKey();
}
// 完成这个函数,使 node1 + node2 得到 两个数字的和的 Node
public static Node CombineNode(Node node1, Node node2)
{
Node maxNode;
Node minNode;
var x = node1.Length - node2.Length;
if (x > 0)
{
maxNode = node1;
minNode = node2;
}
else
{
maxNode = node2;
minNode = node1;
}
//将node1 和 node2 按位相加
Node Add(Node node1, Node node2, ref bool r)
{
var node = new Node();
if (node1.Next == null || node2.Next == null)
{
node.Value = AddChar(node1.Value, node2.Value, ref r);
return node;
}
node.Next = Add(node1.Next, node2.Next, ref r);
node.Value = AddChar(node1.Value, node2.Value, ref r);
return node;
}
var temp = maxNode;
var result = new Node(maxNode.Value);
for (long i = 0; i < Math.Abs(x); i++)
{
temp = temp.Next;
var parent = result.Next;
while (result.Next != null)
{
parent = parent.Next;
}
if (parent != null)
parent.Next = new Node(temp.Next.Value);
else
result.Next = new Node(temp.Next.Value);
}
result.Next = null;
bool r = false;
result.Next = Add(minNode, temp, ref r);
if (result != null)
return result;
return result.Next;
}
static char AddChar(char c1, char c2, ref bool r)
{
var c = int.Parse(c1.ToString()) + int.Parse(c2.ToString());
if (r)
{
c++;
r = false;
}
if (c > 9)
{
r = true;
return c.ToString()[1];
}
else return c.ToString()[0];
}
}
public class Node
{
public char Value { get; set; } = '0';
public Node Next { get; set; }
public Node() { }
public Node(char value)
{
Value = value;
}
public override string ToString()
{
if (Next != null)
return Value.ToString() + Next.ToString();
return Value.ToString();
}
public long Length
{
get
{
if (Next == null)
return 0;
return Next.Length + 1;
}
}
}
网友评论