如何获得与逐位操作整数的第N位?

编程入门 行业动态 更新时间:2024-10-24 14:15:33
本文介绍了如何获得与逐位操作整数的第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位?

本文发布于:2023-11-30 01:32:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648276.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   如何获得   操作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!