Tricky Google interview question

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

    Dijkstra derives an eloquent solution in "A Discipline of Programming". He attributes the problem to Hamming. Here is my implementation of Dijkstra’s solution.

    int main()
    {
        const int n = 20;       // Generate the first n numbers
    
        std::vector v(n);
        v[0] = 1;
    
        int i2 = 0;             // Index for 2
        int i5 = 0;             // Index for 5
    
        int x2 = 2 * v[i2];     // Next two candidates
        int x5 = 5 * v[i5];
    
        for (int i = 1; i != n; ++i)
        {
            int m = std::min(x2, x5);
            std::cout << m << " ";
            v[i] = m;
    
            if (x2 == m)
            {
                ++i2;
                x2 = 2 * v[i2];
            }
            if (x5 == m)
            {
                ++i5;
                x5 = 5 * v[i5];
            }
        }
    
        std::cout << std::endl;
        return 0;
    }
    

提交回复
热议问题