查找数字的特定数字
我正在尝试查找任意长度整数的第 n 位数字。我打算将整数转换为字符串并使用索引 n 处的字符...
char Digit = itoa(Number).at(n);
...但是后来我意识到 itoa
函数不是标准的。还有其他方法可以做到这一点吗?
I'm trying to find the n
th digit of an integer of an arbitrary length. I was going to convert the integer to a string and use the character at index n...
char Digit = itoa(Number).at(n);
...But then I realized the itoa
function isn't standard. Is there any other way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
(number/intPower(10, n))%10
只需定义函数
intPower
。(number/intPower(10, n))%10
just define the function
intPower
.您还可以在循环中使用 % 运算符和 / 进行整数除法。 (给定整数 n >= 0,n % 10 给出个位数,n / 10 去掉个位数。)
You can also use the % operator and / for integer division in a loop. (Given integer n >= 0, n % 10 gives the units digit, and n / 10 chops off the units digit.)
您可以使用 ostringstream 转换为文本字符串,但是
类似以下的函数:
应该能够以更少的复杂性完成任务。 (为了
首先,它处理 n 大于数字的情况
正确的数字。)
--
詹姆斯·坎泽
You can use ostringstream to convert to a text string, but
a function along the lines of:
should do the trick with a lot less complications. (For
starters, it handles the case where n is greater than the number
of digits correctly.)
--
James Kanze
Itoa 位于 stdlib.h 中。
您还可以使用替代 itoa:
替代 itoa() 将整数转换为字符串 C++?
或
ANSI C,不带可变参数函数的整数到字符串
Itoa is in stdlib.h.
You can also use an alternative itoa:
Alternative to itoa() for converting integer to string C++?
or
ANSI C, integer to string without variadic functions
还可以通过函数 log10 int cmath 来避免转换为字符串,该函数返回数字的 10 底对数(如果是的话,则大致是其长度)一个字符串):
我已经测试过它,并且工作得很好(负数是一种特殊情况)。另外,必须考虑到,为了找到第 n 个元素,您必须在循环中向后“走”,从总 int length 中减去。
希望这有帮助。
It is also possible to avoid conversion to string by means of the function log10, int cmath, which returns the 10th-base logarithm of a number (roughly its length if it were a string):
I have tested it, and works perfectly well (negative numbers are a special case). Also, it must be taken into account that, in order to find tthe nth element, you have to "walk" backwards in the loop, subtracting from the total int length.
Hope this helps.
直接的答案是:
您应该包含
库
A direct answer is:
You should include the
<math>
library假设
number.at(n)
返回 0...9 范围内的十进制数字。Assuming
number.at(n)
returns a decimal digit in the range 0...9, that is.更通用的方法:
只是让您对不同的基数(例如 16、32、64 等)执行相同的操作。
A more general approach:
Just lets you do the same thing for different base numbers (e.g. 16, 32, 64, etc.).
itoa
的替代方案是std: :to_string
方法。所以,你可以简单地这样做:An alternative to
itoa
is thestd::to_string
method. So, you could simply do: