var digitToSubstitute = 5;
var targetNumber = 999999999;
var expectedOutput = 995999999;
如何在不將其轉換為字串的情況下替換 int32 中的第 n 個數字?
雖然這是一個小示例,但在現實生活中的應用程式中,我在一個緊密的回圈中使用它(創建所有可能的數字組合并檢查現有的組合),所以我想避免創建字串。
uj5u.com熱心網友回復:
你可以做這樣的事情。與字串操作相比,不確定它的性能如何。
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
注意:不適用于負數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/531136.html
標籤:C#。网细绳代替整数
上一篇:python一種在與字串條件匹配的200萬多個資料串列中查找索引的更快方法
下一篇:EJS檔案可以接收物件嗎?
