Search code examples
algorithmlanguage-agnosticnumber-theory

Fastest way to modify one digit of an integer


Suppose I have an int x = 54897, old digit index (0 based), and the new value for that digit. What's the fastest way to get the new value?

Example

x = 54897
index = 3
value = 2
y = f(x, index, value) // => 54827

Edit: by fastest, I definitely mean faster performance. No string processing.


Solution

  • In simplest case (considering the digits are numbered from LSB to MSB, the first one being 0) AND knowing the old digit, we could do as simple as that:

    num += (new_digit - old_digit) * 10**pos;
    

    For the real problem we would need:

    1) the MSB-first version of the pos, that could cost you a log() or at most log10(MAX_INT) divisions by ten (could be improved using binary search).

    2) the digit from that pos that would need at most 2 divisions (or zero, using results from step 1).

    You could also use the special fpu instruction from x86 that is able to save a float in BCD (I have no idea how slow it is).

    UPDATE: the first step could be done even faster, without any divisions, with a binary search like this:

    int my_log10(unsigned short n){
        // short: 0.. 64k -> 1.. 5 digits 
        if (n < 1000){  // 1..3
            if (n <  10) return 1;
            if (n < 100) return 2;
            return 3;
        } else { // 4..5
            if (n < 10000) return 4;
            return 5;
        }
    }