如何在整数末尾添加两位数字而不转换为字符串?



我有一个整数 id 生成器,我想在每个 id的末尾添加两位数,假设 id 是20120719,并将56添加到 id,那么结果是2012071956.

我可以将两个整数转换为字符串,将字符串中的两个数字连接起来,然后将结果转换为整数,但这看起来效率低下。

在 C# 中执行此操作的最佳做法是什么?

假设您使用的整数类型足够大,简单的数学就可以:

var result = 20120719 * 100 + 56;

在做这样的事情时验证你的不变量是个好主意,这样你就可以正确处理你意外得到 156 而不是 56 的情况。更通用的函数可能如下所示:

static int AddSuffixToId(int id, int suffix)
{
if (id < 0) throw new ArgumentOutOfRangeException(nameof(id));
if (suffix < 0 || suffix >= 100) throw new ArgumentOutOfRangeException(nameof(suffix));
// If we get an overflow, we need to know about it; by default, 
// overflows are silently ignored
checked
{
return id * 100 + suffix;
}
}

最新更新