0
var digitToSubstitute = 5;

var targetNumber   = 999999999;
var expectedOutput = 995999999;

How do I replace the n-th digit in an int32 without converting it to/from a string?

While this is a small sample, in real-life application I use this in a tight loop (to create all possible number combinations and check against existing ones), so I'd like to avoid creating strings.

gunr2171
  • 16,104
  • 25
  • 61
  • 88
Nick Farsi
  • 366
  • 4
  • 19
  • Is `digidToSubstitute` a random number below 10? Does `targetNumber` alsway consist out of 9 digits? – Willem Nov 09 '22 at 20:53
  • And `999999999` can be `382746589` at some point, when you want to change the seventh digid to 5? – Willem Nov 09 '22 at 20:53
  • 2
    Would you be ok converting your big number into an array of single digit numbers? https://stackoverflow.com/questions/829174/is-there-an-easy-way-to-turn-an-int-into-an-array-of-ints-of-each-digit – Kevon Nov 09 '22 at 20:54
  • @CS1061, ```digitToSubstitute``` is a number between 0 and 9 and the ```targetNumber``` always consists of 9 digits – Nick Farsi Nov 09 '22 at 21:00
  • rshepp beated me. – Willem Nov 09 '22 at 21:01
  • It seems like you are manipulating a string, not a number. And the best way to avoid creating strings is to use `StringBuilder`, which you can overwrite in-place as many times as necessary, without creating new garbage. – Ben Voigt Nov 09 '22 at 22:06

1 Answers1

3

You could do something like this. Not sure how this performs compared to string manipulation.

int ReplaceNthDigit(int value, int digitPosition, int digitToReplace, bool fromLeft = false)
{
    if (fromLeft) {
        digitPosition = 1 + (int)Math.Ceiling(Math.Log10(value)) - digitPosition;
    }

    int divisor = (int)Math.Pow(10, digitPosition - 1);
    int quotient = value / divisor;
    int remainder = value % divisor;
    int digitAtPosition = quotient % 10;
    return (quotient - digitAtPosition + digitToReplace) * divisor + remainder;
}

Console.WriteLine(ReplaceNthDigit(999999999, 7, 5, fromLeft: true)); // 999999599
Console.WriteLine(ReplaceNthDigit(999999999, 7, 5, fromLeft: false)); // 995999999

Note: won't work for negative numbers.