The eighth question of Java Blue Bridge Cup 2018

Java Isosceles Triangle

This problem requires you to output an isosceles triangle composed of numbers to the console.
The specific steps are: 1. First use the natural numbers of 1, 2, 3, ... to make a long enough string
2. Use this string to fill the three sides of the triangle. Start at the top vertex and fill in counter-clockwise.

ideas

First understand the meaning of the question. In fact, this question is to use 123456789 10 11 12 to form an isosceles triangle in a certain order. So we have to find a rule; very simple, this rule is that the length of the bottom line is equal to 2N-1, and then the length of the number we need is (2n-3) + 2n-1. This rule is found by itself. Knowing this rule is easy to see the code. So here we can count the numbers according to this rule.

public static void main(String[] args) {
    
    
        int n = sc.nextInt();
        int sum =2n-3+2n-1//算出所需要的字符
        String str = "";
        for (int i = 1; str.length() < sum; i++) {
    
    
            str += String.valueOf(i);
        }
        char[] ch = str.substring(0, sum).toCharArray();
 
        // 第一行
        for (int j = 0; j < n - 1; j++) {
    
    
            System.out.print(".");
        }
        System.out.println(1);
 
        // 第二行~第n-1行
        for (int i = 1; i < n - 1; i++) {
    
    
            for (int j = 0; j < n - i - 1; j++) {
    
    
                System.out.print(".");
            }
 
            System.out.print(ch[i]);
 
            for (int j = 0; j < i * 2 - 1; j++) {
    
    
                System.out.print(".");
            }
 
            System.out.println(ch[sum - i]);
        }
 
        //第n行
        for (int i = n - 1; i < sum - n + 2; i++) {
    
    
            System.out.print(ch[i]);
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325058101&siteId=291194637