代码之家  ›  专栏  ›  技术社区  ›  Dan

确定任何基础的位置值

  •  4
  • Dan  · 技术社区  · 17 年前

    我正在寻找一个函数,该函数将确定给定数字和基数的位置的值。例如

    鉴于:

    Whole Value: 1120
    Base: 10
    Place: Tens place
    

    应返回:

    有人知道这方面的数学吗?

    编辑:该函数还应以数字形式传递整个值,而不是像“e328fa”之类的字符串。此外,返回值也应该是数字,因此FindInPlace(60(整数值)、16(基数)、2(位置、基于1的索引))应该返回3。

    5 回复  |  直到 17 年前
        1
  •  3
  •   Daniel LeCheminant    17 年前

    如果数字已转换为整数(即以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 s地点“或” 1. s 16 256 “s”,你就是这么做的

    digit = log(PlaceValue, base);
    

    或者将代码重写为

    char FindPlace(int number, int base, int digitAsBaseToAPower)
    {
        // TODO: Error checking
        return digits[(number / digitAsBaseToAPower) % base];
    }
    
        2
  •  3
  •   Theran    17 年前

    对于基于1的位置索引,公式为:

    placeval=楼层(编号/(底座^(位置1)))模块底座

    在Python中:

    def FindInPlace(number, base, place):
        return number//base**(place-1) % base
    
        3
  •  3
  •   Scottie T    17 年前
    int getPlace(float x, float place) {
    
        return (int)(x/place) % 10;
    }
    

    这适用于10进制,可以处理小数点左右的位置。您可以这样使用它:

    place = getPlace(1120,10);
    otherPlace = getPlace(0.1120,1e-3);
    

        4
  •  1
  •   Scottie T    17 年前

    像这样的?

    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是从右边开始的数字的基于一的索引。

        5
  •  0
  •   eleven81    17 年前

    以下方法, placeValue ,返回一个 烧焦 ,因为基数11-36的位数大于9。该方法期望:

    • int值:
    • 整数基: 要将整数转换为的基数;可接受值为2-36
    • 地点:

    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;
        }