PTA:L1-002 打印沙漏

26 篇文章 0 订阅
2 篇文章 0 订阅

L1-002 打印沙漏

分数 20

本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印

*****
 ***
  *
 ***
*****

所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。

给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。

输入格式:

输入在一行给出1个正整数N(≤1000)和一个符号,中间以空格分隔。

输出格式:

首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。

输入样例:

19 *

输出样例:

*****
 ***
  *
 ***
*****
2

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

本题的解题思路:根据输入的N,找到最上面一行所需要打印的个数,然后根据格式打印即可。

具体代码如下:C++实现

#include <iostream>

using namespace std;
void L1_002_print_hourglass()
{
    int num;
    char str;
    cin>> num >> str;

    int cnt = 1;
    int temp =1;
    int res = 0;

    while(temp <= num)
    {
        res = num-temp;  //记录剩余个数
        temp += 2 * (2*cnt + 1); 
        cnt++;
    }
    cnt = cnt - 1; //记录打印的行数
    for(int i = 0;i<cnt;i++)
    {
        int c = 2*(cnt-i-1) + 1;
        for(int j = 0;j<i;j++)
        {
            cout << " ";
        }
        for(int k = 0;k<c;k++)
        {
            cout << str;
        }
        cout << endl;
    }
    for(int i = 1;i<cnt;i++)
    {
        int c = 2*i +1;
        for(int j = 0;j<cnt-i-1;j++)
        {
            cout << " ";
        }
        for(int j = 0;j<c;j++)
        {
            cout << str;
        }
        cout <<endl;
    }
    cout << res;

}



int main()
{
    L1_002_print_hourglass();
    return 0;
}

Python代码实现:

a = input()
num =(a.split(" ")[0])
char1 = a.split(" ")[-1]
num1 = int(num)

cnt = 1
temp = 1
res = 0

while(temp <= num1):
   res = num1 - temp
   temp = temp + 2*(2*cnt + 1)
   cnt = cnt + 1

cnt = cnt -1

for i in range(cnt):
    c = 2*(cnt-i) -1
    for j in range(i):
        print(" ",end="")
    while(c):
        print(char1,end="")
        c = c - 1
    print("\n",end="")

for i in range(1,cnt):
    c = 2*i+1

    for j in range(cnt-1-i):
        print(" ",end="")

    while (c):
        print(char1, end="")
        c = c - 1
    print("\n",end="")

print(res)

有什么问题,欢迎私聊我!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aurora_U

谢谢你的鼓励,我会继续努力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值