#字符串或数组表示大数
class Solution:
def print1ToMaxOfNDigits(self, n):
def addOne(num):
isOverflow = False
takeOver = 0
nLength = len(num)-1
for i in range(nLength-1 , -1, -1):
nSum = ord(num[i]) - ord('0') + takeOver
if i == nLength - 1:
nSum += 1
if nSum >= 10:
if i == 0:
isOverflow = True
else:
nSum -= 10
takeOver = 1
num = num[:i] + chr(ord('0')+nSum) + num[i+1:]
else:
num = num[:i] + chr(ord('0') + nSum) + num[i+1:]
break
return isOverflow, num
def printCur(num):
isBeginning0 = True
nLength = len(num)
for i in range(nLength-1):
if isBeginning0 and num[i] != '0':
isBeginning0 = False
if not isBeginning0:
print(num[i], end='')
print('\n', end='')
if n <= 0:return
num = "0" * (n+1)
num = num[:n] + 'e' + num[n+1:]
while True:
isOverflow, num = addOne(num)
if isOverflow:break
printCur(num)
#递归解法
def print1ToMaxOfNDigits(self, n):
def printCur(num):
isBeginning0 = True
nLength = len(num)
for i in range(nLength-1):
if isBeginning0 and num[i] != '0':
isBeginning0 = False
if not isBeginning0:
print(num[i], end='')
print('\n', end='')
def print1ToMaxOfNDigitsRecursively(num, length, index):
if index == length - 1:
printCur(num)
return
for i in range(10):
num = num[:index+1] + chr(i + ord('0')) + num[index+2:]
print1ToMaxOfNDigitsRecursively(num, length, index+1)
if n <=0:return
num = "0" * (n + 1)
num = num[:n] + 'e' + num[n+1:]
for i in range(10):
num = chr(i + ord('0')) + num[1:]
print1ToMaxOfNDigitsRecursively(num, n, 0)
考点