Tricky Google interview question

前端 未结 21 1706
花落未央
花落未央 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:00

    If we are allowed to use java Collection then we can have these number in O(n^2)

    public static void main(String[] args) throws Exception {
        int powerLimit = 7;  
         int first = 2;
         int second = 5;
        SortedSet set = new TreeSet();
    
        for (int i = 0; i < powerLimit; i++) {
            for (int j = 0; j < powerLimit; j++) {
                Integer x = (int) (Math.pow(first, i) * Math.pow(second, j));
                set.add(x);
            }
        }
    
        set=set.headSet((int)Math.pow(first, powerLimit));
    
        for (int p : set)
            System.out.println(p);
    }
    

    Here powerLimit has to be initialised very carefully !! Depending upon how many numbers you want.

提交回复
热议问题