【PTA】L1-002 打印沙漏

https://pintia.cn/problem-sets/994805046380707840/problems/994805145370476544

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

思路:计算最顶部的符号数量,然后依次向下递减两个单位长度,空格数初始为 0 ,依次递增。

计算顶部符号数量:对应到数字 5 3 1 3 5 可以发现都是奇数且都是对称的,我们可以依次累加 i × 2 i \times 2 i×2 ,其中 i 是奇数,直到总和达到 N 的极限值时为止,i 就是顶部最大值。

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StreamTokenizer st = new StreamTokenizer(br);
    static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));

    static int save = 0;

    public static void main(String[] args) throws Exception {
        int n = nextInt();
        char ch = (char) br.read();
        int top = fun(n), empty = 0;
        int cur = top;
        if(top == 0) {
            System.out.println(ch);
            System.out.println(n - save);
            return;
        }
        while(cur >= 0) {
            for(int i = 1; i <= empty; i++) out.print(" ");
            for(int i = 1; i <= cur; i++) out.print(ch);
            cur -= 2;
            empty++;
            out.println();
        }
        cur = 3;
        empty -= 2;
        while(cur <= top) {
            for(int i = 1; i <= empty; i++) out.print(" ");
            for(int i = 1; i <= cur; i++) out.print(ch);
            cur += 2;
            empty--;
            out.println();
        }
        out.println(n - save);
        out.flush();
    }

    public static int fun(int n) {
        int sum = 1, res = 0;
        save = sum;
        for(int i = 3; i <= n; i++) {
            if(i % 2 != 1) continue;
            sum += 2 * i;
            if(sum == n) {
                res = i;
                save = sum;
                break;
            }
            if(sum > n) {
                res = i - 2;
                save = sum - i * 2;
                break;
            }
        }
        return res;
    }

    public static int nextInt() throws Exception {
        st.nextToken();
        return (int) st.nval;
    }
    public static String nextStr() throws Exception {
        st.nextToken();
        return st.sval;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值