如何获得与逐位操作整数的第N位? [英] How to get the Nth digit of an integer with bit-wise operations?

查看:161
本文介绍了如何获得与逐位操作整数的第N位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为例。 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位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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