You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现2的幂次三角形的格式对齐问题求助

How to Align a Symmetric Triangle of Powers of 2 Correctly in Java

Problem Description

I want to generate a symmetric triangle made up of powers of 2 that stays properly aligned no matter how many digits the numbers have. My current Java code generates the correct values, but when multi-digit numbers (like 16) appear, the console alignment breaks. I'm looking for an efficient solution to fix this alignment issue.

Required Example (Input: 8 rows)

1
      1 2 1
    1 2 4 2 1
  1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
... (subsequent rows follow the symmetric pattern with increasing powers of 2)

My Current Code

import java.util.Scanner;
public class Pyramid2 {
    public static void main(String[] args) {
        int i, j, k, l, a;
        Scanner in = new Scanner (System.in);
        System.out.print("Enter number of rows: ");
        int rows = in.nextInt();
        a = rows;
        int length = ("" + rows).length();
        String str = " %" + length + "s";
        for (i = 1; i <= rows; i++) {
            for (j = a; j > 0; j--) {
                System.out.printf(str, " ");
            }
            for (j = 1; j <= (2*rows); j++) {
                if (j == (rows+1)) {
                    continue;
                }
                if (j < (rows+1)) {
                    k = j;
                } else {
                    k = ((2*rows)-j+1);
                }
                if (k >= (rows+1-i)) {
                    l = (int)Math.pow(2, (i+k-rows-1));
                    String str1 = "" + l;
                    System.out.printf(str, str1);
                }
            }
            a--;
            System.out.println();
        }
    }
}

Current Issue

When inputting 6 rows, the alignment breaks starting from the 5th row where the number 16 (a two-digit number) appears.


Solution

The core problem with your code is that you're using the digit length of the input rows to set the formatting width, but you should instead use the digit length of the largest number in the triangle (which is 2^(rows-1)). This ensures every number and indent space uses the same fixed width, keeping alignment consistent.

Here's the revised code with explanations:

import java.util.Scanner;

public class Pyramid2 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number of rows: ");
        int rows = in.nextInt();
        
        // Step 1: Calculate the largest number in the triangle and its digit length
        int maxNumber = (int) Math.pow(2, rows - 1);
        int maxLength = String.valueOf(maxNumber).length();
        // Use %d for integer formatting (more reliable than %s for numbers)
        String formatStr = "%" + maxLength + "d";

        for (int i = 1; i <= rows; i++) {
            // Step 2: Print leading spaces (each "block" is maxLength wide)
            for (int j = 0; j < rows - i; j++) {
                System.out.printf(formatStr, "");
            }

            // Step 3: Print the left half of the triangle
            for (int j = 0; j < i; j++) {
                int num = (int) Math.pow(2, j);
                System.out.printf(formatStr, num);
            }

            // Step 4: Print the right half of the triangle (excluding the middle element)
            for (int j = i - 2; j >= 0; j--) {
                int num = (int) Math.pow(2, j);
                System.out.printf(formatStr, num);
            }

            System.out.println();
        }
        in.close();
    }
}

Key Improvements:

  • Unified Width Calculation: We first compute maxNumber (the largest value in the triangle) and use its digit length as the fixed width for all formatting. This ensures single-digit and multi-digit numbers take up the same horizontal space.
  • Simplified Triangle Construction: Instead of using a complex loop over 2*rows elements, we split the triangle into left and right halves for easier readability and maintainability.
  • Proper Integer Formatting: Using %d instead of %s for numbers ensures consistent formatting, avoiding unexpected spacing issues with string conversions.
  • Cleaner Indentation: Leading spaces are printed as empty "blocks" with the same width as numbers, so each row is properly offset.

Test Result (Input: 6 rows)

1
        1 2 1
      1 2 4 2 1
    1 2 4 8 4 2 1
  1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1

All numbers are perfectly aligned, even with two-digit values like 16 and 32.

内容的提问来源于stack exchange,提问作者RockyMountainCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:26:23