Tricky Google interview question

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

    If you go by what's really happening when we increment i or j in the expression 2^i * 5^j, you are either multiplying by another 2 or another 5. If we restate the problem as - given a particular value of i and j, how would you find the next greater value, the solution becomes apparent.

    Here are the rules we can quite intuitively enumerate:

    • If there is a pair of 2s (i > 1) in the expression, we should replace them with a 5 to get the next biggest number. Thus, i -= 2 and j += 1.
    • Otherwise, if there is a 5 (j > 0), we need to replace it with three 2s. So j -= 1 and i += 3.
    • Otherwise, we need to just supply another 2 to increase the value by a minimum. i += 1.

    Here's the program in Ruby:

    i = j = 0                                                                       
    20.times do                                                                     
      puts 2**i * 5**j
    
      if i > 1                                                                      
        j += 1                                                                      
        i -= 2                                                                      
      elsif j > 0                                                                   
        j -= 1                                                                      
        i += 3                                                                      
      else                                                                          
        i += 1                                                                      
      end                                                                                                                                                               
    end
    

提交回复
热议问题