获取数字所有位数的一个扩展






3.47/5 (10投票s)
获取一个整数的位数和符号,并将其放入数组中
引言
在本技巧中,我将展示一种将整数的所有位数以数组形式返回的方法。
Using the Code
public static class Extensions
{
static int[] Digits(this int value)
{
// get the sign of the value
int sign = Math.Sign(value);
// make the value positive
value *= sign;
// get the number of digits in the value
int count = (int)Math.Truncate(Math.Log10(value)) + 1;
// reserve enough capacity for the digits
int[] list = new int[count];
for (int i = count - 1; i >= 0; --i)
{
// truncate to get the next value
int nextValue = value / 10;
// fill the list in reverse with the current digit on the end
list[i] = value - nextValue * 10;
value = nextValue;
}
// make the first digit the correct sign
list[0] *= sign;
return list;
}
}
关注点
请注意,数组的第一个位置保留了数字的符号。
历史
- 2017年3月9日:第一个版本