Google Interview Q2

Google Interview Q2

Question 2

You are given an integer X. You must choose two adjacent digits and replace them with a single digit that equals to the rounded-up average of these two digits. For example, from the integer X = 623315, you can obtain:

  • 43315(by replacing 62 with 4);
  • 63315(by replacing 23 with 3, since the average of 2 and 3 is 2.5 that is rounded-up to3);
  • 62315(by replacing 33 with 3);
  • 62325(by replacing 31 with 2);
  • 62333(by replacing 15 with 3);

You want to find the largest number that can be obtained from X by replacing two adjacent digits with the rounded-up average of the two. In the above example, the largest such number is 63315. Write a function:

  • def function(X) that, given a positive integer X, returns the largest number that can be obtained from X by replacing two adjacent digits with the rounded-up average of two. For example, given X=623315, the function should return 63315, as explained above. Assume that:
  • X is an integer within the range [10..1,000,000,000]

Solution I Submitted


def solution(X):
    number = [int(i) for i in str(num)]            
    length = len(number) - 1     
    if (len(number) == 2):
        return max(number[0], number[length])
    else:        
        if number[length - 2] > number[length - 1]  and number[length - 1]  > number[length] :
            number[length - 1]  = number[length]
        else:
            number[length- 1] = max(number[length - 1], number[length])
        return reduce(lambda x, y: 10 * x + y, number[0:length], 0)



comments powered by Disqus