为例。 123456,我们希望在右三('4')了。
Example. 123456, and we want the third from the right ('4') out.
在实践中这样做是为了单独访问每个数位(即6 5 4 3 2 1)。
The idea in practise is to access each digit seperately (ie. 6 5 4 3 2 1).
C / C ++ / C#preferred。
C/C++/C# preferred.
推荐答案一个更有效的实现可能是这样的:
A more efficient implementation might be something like this:
char nthdigit(int x, int n) { while (n--) { x /= 10; } return (x % 10) + '0'; }这节省了将所有数字为字符串格式,如果你只想要其中的一个努力。而且,你不必对转换后的字符串分配空间。
This saves the effort of converting all digits to string format if you only want one of them. And, you don't have to allocate space for the converted string.
如果速度是一个问题,你可以precalculate 10次幂的数组,利用N来索引这个数组:
If speed is a concern, you could precalculate an array of powers of 10 and use n to index into this array:
char nthdigit(int x, int n) { static int powersof10[] = {1, 10, 100, 1000, ...}; return ((x / powersof10[n]) % 10) + '0'; }正如其他人所说,这是尽可能接近你会得到位运算的基数为10。
As mentioned by others, this is as close as you are going to get to bitwise operations for base 10.
更多推荐
如何获得与逐位操作整数的第N位?
发布评论