开发者

How to compute value of i-th digit in a k-ary representation of a number?

What is a good algorithm to compute the value of the i-th digit in a 开发者_JAVA百科k-ary representation of a number n?

Example:

For function bitval(int k, int i, int n):

bitval(5, 4, 9730) = 2 because in a 5-ary (quinary) representation of the number 9730 (which is 302410) the 4th digit (from the right) is 2.


Something like:

(n / (k ** i)) % k

(where ** is the exponentiation operator and / is integer (truncating) division) should do it. Use (i-1) if you want to number the digits from the right starting with 1 rather than starting with 0.


The naive algorithm is as follows:

  1. Calculate the k-ary representation of n. This can be achieved with repeated divides and modulo operations.
  2. Return the i-th digit in this representation.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜