• 《剑指offer》第四十四题:数字序列中某一位的数字


    // 面试题44:数字序列中某一位的数字
    // 题目:数字以0123456789101112131415…的格式序列化到一个字符序列中。在这
    // 个序列中,第5位(从0开始计数)是5,第13位是1,第19位是4,等等。请写一
    // 个函数求任意位对应的数字。
    
    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    int countOfIntegers(int digits);
    int digitAtIndex(int index, int digits);
    int beginNumber(int digits);
    
    int digitAtIndex(int index)
    {
        if (index < 0)
            return -1;
    
        int digit = 1;  //位数
        while (true)
        {
            int number = countOfIntegers(digit); //当前位数所有数字
            if (number * digit > index)  //目标是否属于当前位数
                return digitAtIndex(index, digit);
    
            index -= number * digit;
            ++digit;
        }
    }
    
    int countOfIntegers(int digits)  //m位数字总共有多少个
    {
        if (digits == 1)
            return 10;
    
        int number = (int) std::pow(10, digits - 1);
        return 9 * number;
    }
    
    int digitAtIndex(int index, int digits)  //m位数中找到该数字
    {
        int number = beginNumber(digits) + index / digits;  //该m位数中第几个数
        int indexFromRight = digits - index % digits;  //该数第几个数字
        for (int i = 1; i < indexFromRight; ++i)
            number /= 10;
        return number % 10;
    }
    
    int beginNumber(int digits)  //m位数字第一位数字
    {
        if (digits == 1)
            return 10;
    
        int number = (int)std::pow(10, digits - 1);
        return number;
    }
    // ====================测试代码====================
    void test(const char* testName, int inputIndex, int expectedOutput)
    {
        if (digitAtIndex(inputIndex) == expectedOutput)
            cout << testName << " passed." << endl;
        else
            cout << testName << " FAILED." << endl;
    }
    
    
    int main()
    {
        test("Test1", 0, 0);
        test("Test2", 1, 1);
        test("Test3", 9, 9);
        test("Test4", 10, 1);
        test("Test5", 189, 9);  // 数字99的最后一位,9
        test("Test6", 190, 1);  // 数字100的第一位,1
        test("Test7", 1000, 3); // 数字370的第一位,3
        test("Test8", 1001, 7); // 数字370的第二位,7
        test("Test9", 1002, 0); // 数字370的第三位,0
        return 0;
    }
    测试代码

    分析:规律确实可以。

  • 相关阅读:
    关于python urlopen 一个类似radio流的timeout方法
    Python nltk English Detection
    Python依赖打包发布详细
    python 怎么和命令行交互
    Python中多维数组flatten的技巧
    Python中的url编码问题
    python数据持久存储:pickle模块的基本使用
    Python控制台输出不换行(进度条等)
    UnicodeEncodeError: 'ascii' codec can't encode character u'xe9' in position 7: ordinal not in range(128) [duplicate]
    json.loads(s) returns error message like this: ValueError: Invalid control character at: line 1 column 33 (char 33)
  • 原文地址:https://www.cnblogs.com/ZSY-blog/p/12633658.html
Copyright © 2020-2023  润新知