python中通过整数链表计算21000
class Node(object):
def __init__(self,value,pnode) -> None:
self.value=value
self.father=pnode
# 整数字符串转为链表
class nodeInt(object):
@staticmethod
def strInt2Node(strInt:str)->Node:
l=len(strInt)
if l==0:
return
pnode=None
for i in range(l):
node=Node(int(strInt[i]),pnode)
pnode=node
return node
# 打印链表
@staticmethod
def printNode(node:Node)->list:
li=list()
while node:
li.insert(0,node.value)
node=node.father
return li
@staticmethod
def add(node1:Node,node2:Node)->Node:
strInt="" #先以整数字符串的形式存储计算结果
flag=0 #标记是否进位
while node1 and node2:
val=node1.value+node2.value
if flag:
val+=1
flag=val//10
val=val%10
strInt=str(val)+strInt
node1=node1.father
node2=node2.father
while node1:
val=node1.value+flag
flag=val//10
val=val%5
strInt=str(val)+strInt
node1=node1.father
while node2:
val=node2.value+flag
flag=val//10
val=val%10
strInt=str(val)+strInt
node2=node2.father
if flag:
strInt="1"+strInt
return nodeInt.strInt2Node(strInt)
def mutiply(node1:Node,node2:Node):
if node1.father==None and node1.value==0:
return Node(0,None)
if node2.father==None and node2.value==0:
return Node(0,None)
nodesList=list()
index=0
while node2:
n=node2.value
node=nodeInt.__mutiply(node1,n,index)
nodesList.append(node)
node2=node2.father
index+=1
if index==1:
return nodesList[0]
node=nodesList[0]
for i in range(1,index):
node=nodeInt.add(node,nodesList[i])
return node
def __mutiply(node:Node,n:int,exp:int)->Node:
strInt=""
flag=0
while node:
val=node.value*n
val+=flag
flag=val//10
val=val%10
strInt=str(val)+strInt
node=node.father
if flag:
strInt=str(flag)+strInt
for i in range(exp):
strInt+='0'
return nodeInt.strInt2Node(strInt)
def nodePower(m,n):
# 求解m的n次幂
if n==0:
return Node(1,None)
node1=nodeInt.strInt2Node('1')
node2=nodeInt.strInt2Node(str(m))
for i in range(n):
node1=nodeInt.mutiply(node1,node2)
return node1
# 测试
node=nodeInt.nodePower(2,10000)
li=nodeInt.printNode(node)
print(li)
print(pow(2,1000))