https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/
输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数 999。
思路:这道题应该主要是考大数问题,用字符串模拟加法。但是leetcode上这道题没什么意义,直接写也能过
def printNumbers(self, n):
"""
:type n: int
:rtype: List[int]
"""
return range(1, 10 ** n)
class Solution(object):
def printNumbers(self, n):
"""
:type n: int
:rtype: List[int]
"""
max = 0
for i in range(0, n):
max += 9 * pow(10, i) # 尝试了max = int("9" * n) 效率没有这个高
result = list()
i = 1
while i <= max:
result.append(i)
i = i + 1
return result
考虑大数问题
- 用string模拟数值进行运算,需要模拟两部分 1. 用string模拟数值加法 2. 用string比较代替数值大小比较
加法部分思路参考 https://blog.csdn.net/weixin_42219542/article/details/113769802
class Solution(object):
def sum(self, a, b):
# 不考虑性能,就考虑通用性,这里写一个实现string相加的功能
result = ""
result_list = list()
remain = 0
i = 1
while i <= len(a) and i <= len(b):
sum = int(a[-i]) + int(b[-i]) + remain
tmp = sum % 10
remain = sum / 10
result_list.append(tmp)
i += 1
while i <= len(a):
sum = int(a[-i]) + remain
tmp = sum % 10
remain = sum / 10
result_list.append(tmp)
i += 1
while i <= len(b):
sum = int(b[-i]) + remain
tmp = sum % 10
remain = sum / 10
result_list.append(tmp)
i += 1
if remain != 0:
result_list.append(remain)
i = 1
while i <= len(result_list):
result += str(result_list[-i])
i += 1
return result
def printNumbers(self, n):
"""
:type n: int
:rtype: List[int]
"""
max = ""
for i in range(0, n):
max += "9"
# print max
result = list()
i = "0" * n
# print i
while i <= max and len(i) <= len(max):
if i.lstrip('0') == "":
# 过滤掉初始化的0
i = self.sum(i, "1")
continue
result.append(int(i.lstrip('0')))
# 字符串加法
i = self.sum(i, "1")
# print i
return result
2. 全排列法
思路:考虑每个位置的数字都有0-9 10种可能。
初始化n位0字符串,固定高位,向低位递归。
在调试台没问题,但是提交上去不行,很神奇
class Solution(object):
result_list = list()
def addNumbers(self, k, result, result_list, n):
if k >= n:
tmp = ''.join(result) # 这里要是完全考虑大数,就用rstrip去掉开始多余的0,因为这道题输出是int,直接用int函数,就不用去掉开始的0了
if int(tmp) != 0:
self.result_list.append(int(tmp))
return
for i in range(0, 10):
result[k] = str(i)
self.addNumbers(k+1, result, self.result_list, n)
return
def printNumbers(self, n):
"""
:type n: int
:rtype: List[int]
"""
result = [0] * n
self.addNumbers(0, result, self.result_list, n)
return self.result_list
不知道为什么。。。。