Home > Mobile >  How do I replace a digit in an Int32 without turning it into a string?
How do I replace a digit in an Int32 without turning it into a string?

Time:11-10

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.

CodePudding user response:

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.

  • Related