沙漏模型

2019-11-18  本文已影响0人  huangyuanyuan

1、题目地址

https://pintia.cn/problem-sets/17/problems/260

2、题目条件

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

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

输入样例:
19 *

3、代码

import java.util.Scanner;
public class sand {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int count = 0;
        String tag = "";
        try {
          while (in.hasNext()) {
            count = in.nextInt();
            tag = in.next();

            break;
          }
        } catch (NullPointerException ex) {
        
        }
        sand(count,tag);
    
    }
    
    public static void sand( int count , String tag) {
        int tempCount = 0;
        int tempRows = 0;
        int max = 0;
        int outPutCount = 0;
        for( int i = 1 ; tempCount <= count+1 ; i++ ) {
            max = (2*i-1);
            tempCount += max*2;
            tempRows = i;
        }

        if( count > 1) {
            tempRows -=1;
            max-=2;
        }
        
        for( int i =0; i< tempRows-1 ; i++) {
            
            for( int j = 0 ; j < i ; j++) {
                System.out.print(" ");
            }
            for( int j = 0 ; j < max-2*i ; j++) {
                System.out.print(tag);
                outPutCount++;
            }

            System.out.println();
            
        }
        
        for( int i = tempRows; i >0  ; i--) {
            
            for( int j = 1 ; j < i ; j++) {
                System.out.print(" ");
            }
            for( int j = 0 ; j < max-2*(i-1) ; j++) {
                System.out.print(tag);
                outPutCount++;
            }

            System.out.println();
        }
        
        System.out.print(count-outPutCount);    
    }
}

4、问题及总结

  1. 输出格式问题
    输出格式在正常输出的符号后,增加了多余空格,导致结果检查通不过,报格式错误。
  2. 最小值问题
    本机编写代码时没有关注边界问题,这里是简单对边界添加了保护。
  3. 数学公式
    这里没有使用数学公式,是自己计算的行数,有参考其他人做法,使用java数学公式更为简单。
上一篇 下一篇

猜你喜欢

热点阅读