我正在寻找一个能够确定给定数字和基数的地方值的函数。例如,
假设:
Whole Value: 1120 Base: 10 Place: Tens place
应该返回: 2
有人知道这个数学吗?
编辑:该函数也应该以数字方式传递整个值,而不是像“e328fa”之类的字符串。此外,返回值也应该是数字,因此FindInPlace(60(整数值),16(基数),2(地点,1指数))应返回3.
答案 0 :(得分:3)
如果数字已经转换为整数(即基数为10)
// Supports up to base 36
char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char FindPlace(int number, int base, int digit)
{
if(digit < 0) return 0;
// Essentially divide the number by [base] to the [digit] power
for(i=0; i<digit; i++)
{
number /= base;
}
// TODO: Verify that the digit is in range of digits
return digits[number % base];
}
(0
为您提供最正确的数字,1
为您提供最右边的数字,等等。
我已将该数字作为char
返回,以允许超过10的碱基。
请注意,如果您希望允许用户输入所需的数字作为“1
的位置,10
的位置,100
的位置”或“1
s,16
s,256
s“,你只需做
digit = log(PlaceValue, base);
或重写代码
char FindPlace(int number, int base, int digitAsBaseToAPower)
{
// TODO: Error checking
return digits[(number / digitAsBaseToAPower) % base];
}
答案 1 :(得分:3)
int getPlace(float x, float place) {
return (int)(x/place) % 10;
}
这适用于base-10,可以处理小数点右侧或左侧的位置。你会这样使用它:
place = getPlace(1120,10);
otherPlace = getPlace(0.1120,1e-3);
任何基础的更通用的解决方案都很棘手。我会选择一个字符串解决方案。
答案 2 :(得分:3)
使用基于1的位置索引,公式为:
placeval = floor(number /(base ^(place-1)))mod base
在Python中:
def FindInPlace(number, base, place):
return number//base**(place-1) % base
答案 3 :(得分:1)
这样的东西?
int place_value(int value, int base, int place)
{
int value_in_place= value;
for (int place_index= 1; place_index<place; ++place_index)
{
value_in_place/=base;
}
return value_in_place % base;
}
其中place是右边所需数字的从一开始的索引。
答案 4 :(得分:0)
以下方法 placeValue 返回 char ,因为11-36位的数字大于9.该方法需要:
import java.math.BigInteger;
...
private static char placeValue(int value, int base, int place) {
BigInteger bigValue = BigInteger.valueOf(value);
String baseString = bigValue.toString(base);
int numDigits = baseString.length();
int digitIndex = numDigits - place;
char digit = baseString.charAt(digitIndex);
return digit;
}