2016-10-30 142 views
-1

我需要用java打印出一個數字金字塔。它的數量是2的倍數以及下面的數據。但我有它的代碼只能帶出1的倍數沒有空格。java中的數字金字塔。

     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 
1 2 4 8 16 32 64 32 16 8 4 2 1 

這是我的代碼。

import java.util.Scanner; 

public class NumericPyramid { 

    public static void main(String[] args) { 

     Scanner sc = new Scanner(System.in); 

     //Taking noOfRows value from the user 

     System.out.println("How Many Rows You Want In Your Pyramid?"); 

     int noOfRows = sc.nextInt(); 

     //Initializing rowCount with 1 

     int rowCount = 1; 

     System.out.println("Here Is Your Pyramid"); 

     //Implementing the logic 

     for (int i = noOfRows; i > 0; i--) { 
      //Printing i*2 spaces at the beginning of each row 

      for (int j = 1; j <= i*2; j++) { 
       System.out.print(" "); 
      } 

      //Printing j value where j value will be from 1 to rowCount 

      for (int j = 1; j <= rowCount; j++) { 
       System.out.print(j+" "); 
      } 

      //Printing j value where j value will be from rowCount-1 to 1 

      for (int j = rowCount-1; j >= 1; j--) {     
       System.out.print(j+" ");    
      }       

      System.out.println(); 

      //Incrementing the rowCount 

      rowCount++; 
     } 
    } 
} 

輸出:

How Many Rows You Want In Your Pyramid? 

7 

Here Is Your Pyramid 

       1 

      1 2 1 

      1 2 3 2 1 

     1 2 3 4 3 2 1 

     1 2 3 4 5 4 3 2 1 

    1 2 3 4 5 6 5 4 3 2 1 

    1 2 3 4 5 6 7 6 5 4 3 2 1 
+2

如果每次你把'j'加1,你把它加倍?每次你減少一個j,你把它減半? –

+0

你是什麼意思? – zeogold

+0

@DavidWallace我看到你在那裏做了什麼(͡°͜ʖ͡°),OP確實(可悲地)沒有 – Turing85

回答

2

對於從1每個JC你需要寫2道^ Jñ。目前,你只寫j。 所以寫函數給定k返回2^k。

編輯:對於更大的n您需要使用的BigInteger:

import java.math.BigInteger; 

public class NumericPyramid { 
    private static BigInteger pow(int exponent) { 
     BigInteger result = new BigInteger("1"); 
     BigInteger two = new BigInteger("2"); 
     for (int i = 0; i < exponent; i++) { 
      result = result.multiply(two); 
     } 
     return result; 
    } 

,並用它在這兩個for循環。替換

System.out.print(j+" "); 

System.out.print(pow(j)+" "); 
+0

'1 << j'比實現整個'pow()'方法更簡單嗎?並且'pow()'的參數不是* base *,而是* exponent *。該基地硬編碼爲2. – Andreas

+0

該戰略給了我一個錯誤 – zeogold

0

金字塔變爲1 2 4 8 16,這是1×2 = 2的序列,2 * 2 = 4,4 * 2 = 8等等,然後反轉,8/2 = 4,4/2 = 2,2/2 = 1,當中心點只需要乘以2併除以2

for (int i = 0; i < noOfRows; i++) { 
      int cont = 1; 
      for (int j = 0; j <= i; j++) { 
       System.out.print(cont + " "); 
       cont = cont * 2; 
      } 
      cont = cont/2; 
      for (int j = 0; j < i; j++) { 
       cont = cont/2; 
       System.out.print(cont + " "); 
      } 
      System.out.println(); 
     } 
+1

'我* 2/2'的重點是什麼?這與'我'一樣。乘以2然後除以2留下原始數字(除非溢出)。 – Andreas

+0

@Andreas你是對的,只是'我'會做伎倆 –

+0

,只做了金字塔的右半部分 – zeogold