从Int获取个别数字而不使用字符串? [英] Get individual digits from an Int without using strings?

查看:111
本文介绍了从Int获取个别数字而不使用字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道您可以将Int转换为字符串并使用索引器获取位置x处的数字,就像它是一个char数组一样,但是当您处理多个大数字时,这种转换会有点开销。

I know you can convert the Int to a string and get the digit at position x using the indexer as if it was a char array, but this conversion becomes a bit of an overhead when you're dealing with multiple large numbers.

有没有办法在x位置检索数字而不将数字转换成字符串?

Is there a way to retrieve a digit at position x without converting the number to a string?

编辑:

谢谢大家,我将对提出的方法进行基准测试,并检查它是否比转换为字符串更好。如果有人有更好的想法,线程将保持24小时无人接听。

Thank you all, I will benchmark the proposed methods and check if it is any better than converting to a string. Thread will stay unanswered for 24h in case anyone has better ideas.

编辑2:

经过一些简单的测试在ulong数字上,我得出的结论是,与下面提供的方法相比,转换为字符串和提取数字的速度可能会慢50%,请参阅批准的答案。

After some simple tests on ulong numbers, I have concluded that converting to strings and extracting the digit can be up to 50% slower compared to the methods provided below, see approved answer.

推荐答案

你可以这样做:

int ith_digit(int n, int i) {
    return (int) (n / pow(10, i)) % 10;
}

我们可以通过将数字减少到某个点来获得第i个数字我们想要的数字变成一个位置,例如:

We can get the ith digit by reducing the number down to a point where that digit we want becomes in the one's place, example:

假设您想要12345中的第三个数字,然后将其减少到123(将其除以10个数字然后我们可以将该数字的余数除以10得到最后一位数,这是我们想要的数字。

Let's say you wanted the third digit in 12345, then by reducing it to 123 (by dividing it by 10 i number of times) we can then take the remainder of that number divided by ten to get the last digit, which is the digit we wanted.

这篇关于从Int获取个别数字而不使用字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆