Search code examples
algorithmlanguage-agnostic

Remove the inferior digits of a number


Given a number n of x digits. How to remove y digits in a way the remaining digits results in the greater possible number?

Examples:

1)x=7  y=3
n=7816295
  -8-6-95
         =8695

2)x=4  y=2
n=4213
  4--3
      =43

3)x=3  y=1
n=888
     =88

Just to state: x > y > 0.


Solution

  • For each digit to remove: iterate through the digits left to right; if you find a digit that's less than the one to its right, remove it and stop, otherwise remove the last digit.

    If the number of digits x is greater than the actual length of the number, it means there are leading zeros. Since those will be the first to go, you can simply reduce the count y by a corresponding amount.

    Here's a working version in Python:

    def remove_digits(n, x, y):
        s = str(n)
        if len(s) > x:
            raise ValueError
        elif len(s) < x:
            y -= x - len(s)
        if y <= 0:
            return n
        for r in range(y):
            for i in range(len(s)):
                if s[i] < s[i+1:i+2]:
                    break
            s = s[:i] + s[i+1:]
        return int(s)
    
    >>> remove_digits(7816295, 7, 3)
    8695
    >>> remove_digits(4213, 4, 2)
    43
    >>> remove_digits(888, 3, 1)
    88
    

    I hesitated to submit this, because it seems too simple. But I wasn't able to think of a case where it wouldn't work.