The code copy is as follows:
/*Java
*Author: NealFeng at oschina.net
*License: GPLv2+
*Time: 2014/1/17
*
*Output digital pyramid in console:
* 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
*The defect of console output is that the numbers cannot be completely centered, and can only be right or left.
*/
public class NumberPyramid {
public static void main(String[] args) {
// Number of rows
int lineNumber = 5;
// Base
int baseNumber = 2;
// Generate numbers, and the numbers are saved in the array {1,2,4,8,...,2^n}
int[] numbers = new int[lineNumber];
numbers[0]=1;
for(int i = 1; i < lineNumber; i++) {
numbers[i] = numbers[i-1] * baseNumber;
}
// Calculate how many characters each number occupies: the maximum number of digits + 2
int columnsPerNumber =
String.valueOf(numbers[lineNumber-1]).length() + 2;
// Output, the output format is as follows:
// Each indent = columnsPerNumber spaces
// Each number width is columnsPerNumber
// This will form a pyramid-like shape
// Indent Indent Indent Indent Indent Indent Indent Number
// Indent indent in digital numbers
// Indented digits digits
// Digital numbers
for(int i = 0; i < lineNumber; i++) {
//Output indentation
for(int j = 0; j < lineNumber-i-1; j++)
System.out.printf("%"+columnsPerNumber+"s", " ");
//Output number
//Output {1,2,4,8,...,2^n}
for(int k = 0; k < i+1; k++)
System.out.printf("%"+columnsPerNumber+"d", numbers[k]);
//Output {2^n-1,...,8,4,2,1}
for(int m = 0; m < i; m++)
System.out.printf("%"+columnsPerNumber+"d", numbers[im-1]);
//Win
System.out.println();
}
}
}