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
Java解法:
我以位移運算解決
1 2 4 8 16 8 4 2 1
問題
int k = 5;
for (int i = 0; i < k; i++) { System.out.print((1 << i) + " "); }會打印 1 2 4 8 16
for (int j = 0; j < k+1; j++) { System.out.print(((1 << k) >> j) + " "); }再接著打印 8 4 2 1
int num = 5; for (int k = 0; k < num; k++) { //printSpace(num-k); for (int i = 0; i < k; i++) { System.out.print((1 << i) + " "); } for (int j = 0; j < k+1; j++) { System.out.print(((1 << k) >> j) + " "); } System.out.print("\n"); } }
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
這樣子只有直角三角形,只要在打印每行前先打印二格空白" "
就能呈現金字塔了
完整代碼如下
public class Pyramid { public static void main(String[] args) { int num = 5; for (int k = 0; k < num; k++) { printSpace(num-k); for (int i = 0; i < k; i++) { System.out.print((1 << i) + " "); } for (int j = 0; j < k+1; j++) { System.out.print(((1 << k) >> j) + " "); } System.out.print("\n"); } } public static void printSpace(int num) { for (int s = 0; s < num; s++) { System.out.print(" "); } } }
因為是先用python做測試,隨便附上python版
def pyramid(num): for i in range(num): print '\0\0'*(num-i), for j in range(i): print 1<> k, print
沒有留言:
張貼留言