How to get the least number after deleting k digits from the input number

前端 未结 11 1220
灰色年华
灰色年华 2020-12-11 05:34

For example, if the input number is 24635, the least number is 23 after deleting any 3 digits.

It\'s not the same as taking the two smalles

11条回答
  •  生来不讨喜
    2020-12-11 05:59

    Knowing that you want to keep digit order certainly makes this solution more difficult.

    I do agree with IVlad that char[]s are not the way to go.

    I think this is a fairly good solution:

    #include 
    #include 
    #include 
    
    #define DIGITS_TO_REMOVE 3 // Assumed to be positive
    
    int recurse(int* foo, int begin, int end, int previous, int max){
        int i;
        int min = begin;
    
        for (i = begin; i <= end; ++i){
            if (foo[min] > foo[i]){
                min = i;
            }
        }
    
        return previous * pow(10, max - end + 1) + (max > end ? recurse(foo, min + 1, end + 1, foo[min], max) : foo[min]);
    }
    
    int main(void) {
        int foo[(const int)ceil(log10(INT_MAX))];
        int bar = 24635; // Assumed to be larger than pow(10, DIGITS_TO_REMOVE) - 1
        int size = ceil(log10(bar));
        int i;
        int min = size - DIGITS_TO_REMOVE;
    
        for (i = 1; bar > 0; bar /= 10, ++i){
            foo[size - i] = bar % 10;
    
            if (i >= DIGITS_TO_REMOVE && foo[size - i] <= foo[min]){
                min = size - i;
            }
        }
    
        printf("%d", recurse(foo, min + 1, DIGITS_TO_REMOVE + 1, foo[min], size - 1));
        return 0;
    }
    

    EDIT:

    IVlad also suggested that I make the solution return an array rather than just an int so it wouldn't be constrained to the size of the return type. There is obviously some work that would need to go into preparing the input and output array so that may not be the goal of the OP, but it's an interesting problem.

    #include 
    
    #define DIGITS_TO_REMOVE 3 // Assumed to be positive
    #define INPUT_SIZE 5 // Assumed to be greater than DIGITS_TO_REMOVE
    
    void recurse(int* input, int* output, int begin, int end){
        int i;
        int min = begin;
    
        for (i = begin; i < end; ++i){
            if (input[min] > input[i]){
                min = i;
            }
        }
        output[end - DIGITS_TO_REMOVE - 1] = input[min];
    
        if (end < INPUT_SIZE){
            recurse(input, output, min + 1, end + 1);
        }
    }
    
    int main(void) {
        int foo[] = { 2, 4, 6, 3, 5 };
        int bar[INPUT_SIZE - DIGITS_TO_REMOVE];
        int i;
    
        recurse(foo, bar, 0, DIGITS_TO_REMOVE + 1);
    
        for (int i = 0; i < INPUT_SIZE - DIGITS_TO_REMOVE; ++i){
            printf("%d", bar[i]);
        }
        return 0;
    }
    

提交回复
热议问题