-1

I am trying to generate pascal's triangle using powers of 11 but it works only till 4 and after 4 code needs to be modified to achieve further part of the triangle. Any leads for the answer(if possible through this method) are appreciated.

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> a = new ArrayList<List<Integer>>();
        for (int i = 0; i < numRows; i++) {
            List<Integer> b = new ArrayList<Integer>(i);
            int c = (int) (Math.pow(11, i));
            while (c > 0) {
                int d = c % 10;
                b.add(d);
                c = c / 10;
            }
            a.add(b);
        }
        return a;
    }
}
Community
  • 1
  • 1
Venkatesh Gotimukul
  • 741
  • 1
  • 9
  • 30

2 Answers2

1

You are adding numbers to the ArrayList in reverse order, so before adding the inner list to outer, just reverse it.

while (c > 0) {
    int d = c % 10;
    b.add(d);
    c = c / 10;
}
Collections.reverse(b);
a.add(b);
Amal K
  • 4,359
  • 2
  • 22
  • 44
Y.Kakdas
  • 833
  • 7
  • 17
  • I guess it doesn't matter till 4 since all the numbers generated are palindromic..1,11,121,1331,14641. The problem comes after 5 and i guess this method works only till 4. – Venkatesh Gotimukul Mar 01 '19 at 17:15
  • 1
    I did not mention that the algorithm you use it correct for the pascal triangle but the adding numbers in reverse order was the problem in your code in the manner of programming. Your problem was why not 11^5 is different than to the real value, I just tried to fix it. – Y.Kakdas Mar 02 '19 at 18:16
1

Sadly, the power of 11 works up to 5th line and ends right there because of regrouping (there is a 10 so it "carries").

Ex: Expect 11^5 = 1|5|10|10|5|1 But we get 11^5 = 161051

You can follow different approach for printing pascal triangle.

Optimize Way of finding pascal triangle:

karthikmunna
  • 139
  • 1
  • 2
  • 14