2016-08-09 82 views
-2
1 
2 3 
4 5 6 

我必須使用single for循環打印三角形。在Java中使用單個for循環打印三角形

我已經嘗試使用兩個循環,我成功了,但我必須解決它使用單循環。

+0

爲什麼你需要做單迴路?即使你用一個循環或多個循環做同樣的事情,複雜性仍然是一樣的! –

回答

0

試試這個。

public class Pyramid7Floyds { 
    public static void main(String[] args) { 


      int nextNumber = 1; 
      for (int i = 1; i <= 10; i++) { 
        for (int j = 1; j <= i; j++) { 
         System.out.print(nextNumber<10 ? (" " + nextNumber++) : (" " + nextNumber++)); //2spaces in single digit & 1 space in double digit. 
         //System.out.format("%3d",nextNumber++); //You may use this line for formatting as a replacement of above line. (comment above line before using this) 
        } 
        System.out.println(); 
      } 


    } 
} 
0
public class HelloWorld{ 

    public static void main(String []args){ 
     int j=1; 
     for(int i=1;i<=6;i++){ 
      System.out.print(i+" "); 
      if (i==j){ 
       System.out.print('\n'); 
       j=2*j+1; 
      } 
     } 
    } 
} 
1

的訣竅是,最後一個數字當前行前一行最後一個數字之和的數行

的在其他詞:lastNum = prevLastNumber + rowNum

int row = 1; 
int last = 0; 
for (int i = 1; i < 37; i++) { 
    if (i < (row + last)) { 
     System.out.print(i + " "); 
    } else { 
     System.out.print(i + "\n"); 
     row++; 
     last = i; 
    } 
} 

和輸出如下:

1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 21 
22 23 24 25 26 27 28 
29 30 31 32 33 34 35 36