Tricky Google interview question

前端 未结 21 1694
花落未央
花落未央 2020-12-22 15:39

A friend of mine is interviewing for a job. One of the interview questions got me thinking, just wanted some feedback.

There are 2 non-negative integers: i and j. Gi

21条回答
  •  不思量自难忘°
    2020-12-22 16:14

    If you draw a matrix with i as the row and j as the column you can see the pattern. Start with i = 0 and then just traverse the matrix by going up 2 rows and right 1 column until you reach the top of the matrix (j >= 0). Then go i + 1, etc...

    So for i = 7 you travel like this:

    7, 0 -> 5, 1 -> 3, 2 -> 1, 3
    

    And for i = 8:

    8, 0 -> 6, 1 -> 4, 2 -> 2, 3 -> 0, 4
    

    Here it is in Java going up to i = 9. It prints the matrix position (i, j) and the value.

    for(int k = 0; k < 10; k++) {
    
        int j = 0;
    
        for(int i = k; i >= 0; i -= 2) {
    
            int value = (int)(Math.pow(2, i) * Math.pow(5, j));
            System.out.println(i + ", " + j + " -> " + value);
            j++;
        }
    }
    

提交回复
热议问题