数字反转打印
标题:数字反转打印 | 时间限制:1秒 | 内存限制:262144K |
小华是个很有对数字很敏感的小朋友,他觉得数字的不同排列方式有特殊美感。某天,小华突发奇想,如果数字多行排列,第一行1个数,第二行2个,第三行3个,即第n行有n个数字,并且奇数行正序排列,偶数行逆序排列,数字依次累加。这样排列的数字一定很有意思。聪明的你能编写代码帮助小华完成这个想法吗?
while True: try: n, res = int(input()), "" for i in range(1, n + 1): big = (i + 1) * i //2 small = big + 1 - i if n == 1: res = "1" + "*" * 3 continue cul_ls = list() for j in range(small, big + 1): length = 4 - len(str(j)) cul_ls.append(f"{j}{'*'*length}") cul_ls = cul_ls if i % 2 != 0 else cul_ls[::-1] res += (n - i) * 4 * " " + (" " * 4).join(cul_ls) + "\n" print(res) except: break
#include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; int main() { int n; cin>>n; int num = 1; for (int i = 1; i <= n; i++) { string ans; for (int j = 0; j < i; j++) { string strnum = to_string(num); num++; int xlen = 4 - strnum.size(); if (i % 2 == 1) { ans += strnum + string(xlen, '*') + string(4, ' '); } else { reverse(strnum.begin(), strnum.end()); ans += string(4, ' ') + string(xlen, '*') + strnum; } } if (i % 2 == 0) { reverse(ans.begin(), ans.end()); } for (int j = 0; j < 4; j++) { ans.pop_back(); } cout<<string((n - i) * 4, ' '); cout<<ans<<endl; } return 0; }