【面试题17】打印从1到最大的n位数

在这里插入图片描述
Python题解

#字符串或数组表示大数
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)

考点

  • 考查解决大数问题的能力。
  • 判断是否已经到达最大n位数的方法。
  • 使用递归方法解决问题的能力
  • 打印数字会不会打印数字前面的0。

你可能感兴趣的:(朱滕威的面试之路)