Joh*_*ith 31 numbers bit-manipulation
例.123456,我们希望第三个从右边('4')出来.
实践中的想法是单独访问每个数字(即6 5 4 3 2 1).
C/C++/C#首选.
Gre*_*ill 38
更有效的实现可能是这样的:
char nthdigit(int x, int n)
{
while (n--) {
x /= 10;
}
return (x % 10) + '0';
}
Run Code Online (Sandbox Code Playgroud)
如果您只需要其中一个数字,这可以节省将所有数字转换为字符串格式的工作量.而且,您不必为转换后的字符串分配空间.
如果速度是一个问题,你可以预先计算10的幂的数组并使用n索引到这个数组:
char nthdigit(int x, int n)
{
static int powersof10[] = {1, 10, 100, 1000, ...};
return ((x / powersof10[n]) % 10) + '0';
}
Run Code Online (Sandbox Code Playgroud)
正如其他人所提到的,这就像你要对基数10进行按位运算一样接近.
使用以10为底的数学:
class Program
{
static void Main(string[] args)
{
int x = 123456;
for (int i = 1; i <= 6; i++)
{
Console.WriteLine(GetDigit(x, i));
}
}
static int GetDigit(int number, int digit)
{
return (number / (int)Math.Pow(10, digit - 1)) % 10;
}
}
Run Code Online (Sandbox Code Playgroud)
产生:
6
5
4
3
2
1
Run Code Online (Sandbox Code Playgroud)
刚刚花时间在这里根据答案写这个,所以我想分享.
这是基于Brannon的答案,但一次可以让你获得多个数字.在我的例子中,我使用它从保存在int中的日期和时间中提取部分,其中数字是yyyymmddhhnnssm_s格式.
public static int GetDigits(this int number, int highestDigit, int numDigits)
{
return (number / (int)Math.Pow(10, highestDigit - numDigits)) % (int)Math.Pow(10, numDigits);
}
Run Code Online (Sandbox Code Playgroud)
我把它作为一个扩展,你可能不想,但这里是样本用法:
int i = 20010607;
string year = i.GetDigits(8,4).ToString();
string month = i.GetDigits(4,2).ToString();
string day = i.GetDigits(2,2).ToString();
Run Code Online (Sandbox Code Playgroud)
结果:
年= 2001年
月= 6
天= 7
Sma*_*acL -2
在 C 中,你可以执行如下操作,其中 n=0 表示最右边的数字
char nthDigitFromRight(int x,int n)
{
char str[20];
sprintf(str,"%020d",x);
return(str[19 - x]);
}
Run Code Online (Sandbox Code Playgroud)
如果您希望最右边的数字 n=1,请将 [19-x] 更改为 [20-x]。
| 归档时间: |
|
| 查看次数: |
46222 次 |
| 最近记录: |