当我们 输入:10
输出:01 02 03 04 05 06 07 08 09 10
当我们 输入:103
输出:001 002 003 ... 010 011 012 013 ..... 100 101 002 103
如何在ruby或python中创建这个序列?
答案 0 :(得分:2)
Ruby实现:
n = gets
p (1..n.to_i).map{ |i| i.to_s.rjust(n.to_s.length, "0") }.join(" ")
此处rjust
将添加前导零。
答案 1 :(得分:2)
Ruby中的另一个:
tell application "System Events" to tell process "myapp"
-- set frontmost to true
tell window 1
tell group1
exists text field
end tell
end tell
end tell
String#upto
以特殊方式处理数字字符串:
n = gets.chomp
'1'.rjust(n.size, '0').upto(n) { |s| puts s }
答案 2 :(得分:1)
一个非常基本的Python实现。请注意,它是一个生成器,因此它一次返回一个值。
def get_range(n):
len_n = len(str(n))
for num in range(1, n + 1):
output = str(num)
while len(output) < len_n:
output = '0' + output
yield output
for i in get_range(100):
print(i)
>> 001
002
...
...
009
010
011
..
..
099
100
答案 3 :(得分:1)
使用zfill
您可以添加前导零。
num=input()
for i in range(1,int(num)+1):
print (str(i).zfill(len(num)))