• 数字序列中某一位的数字


    题目

      数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从0开始计数)是5,第13位是1,第19位是4,等等。请写一个函数,求任意第n位对应的数字。

    思路

    跳过不同位数的数字,在相应位数中寻找,以序列中第1001(记为index)位为例: 

    1. 序列前10位为0-9,1001>10,跳过,更新index的值为991,再从后面991位;
    2. 后面180位为10-99,跳过,更新index的值为811,再从后面找811位;
    3. 后面2700位为100-999,因为811<2700,所以811位是某个三位数中的一位;
    4. 由于811=270*3+1,这就是说811位是从100开始的第270个数字即370的中间一位,即7。(注意,这里都是从第0位开始计数的)
    #include <iostream>
    #include <cmath>
    using namespace std;
    
    class Solution
    {
        public:
            int digit_at_index(int index);
            int digit_at_index(int index,int digit);
            int count_of_intger(int digit);
            int begin_num(int digit);
    };
    int Solution::digit_at_index(int index)
    {
        if(index<0)
            return -1;
        int digit=1;
        while(true)
        {
            int num=count_of_intger(digit);
            if(index<digit*num)
                return digit_at_index(index,digit);
                
            index-=digit*num;
            ++digit;
        }
    }
    int Solution::digit_at_index(int index,int digit)
    {
        int num=begin_num(digit)+index/digit;
        int format=digit-index%digit;//从这个数字的最后一位开始找要找的数字 
        for(int i=1;i<format;++i)
            num/=10;
        return num%10;
    }
    int Solution::begin_num(int digit)
    {
        if(digit==1)
            return 0;
        return (int)pow(10,digit-1);
    }
    int Solution::count_of_intger(int digit)
    {
        if(digit==1)
            return 10;
        
        int count=(int)pow(10,digit-1);
        return count*9;
    }
    int main()
    {
        int n;
        cin>>n;
    
        Solution s;
        cout<<s.digit_at_index(n)<<endl;
        return 0;
    }

     

  • 相关阅读:
    LeetCode 169. Majority Element
    Object-c block块
    Object-c动态特性
    Object-c基础(2)
    Object-c基础
    LeetCode171:Excel Sheet Column Number
    LeetCode242:Valid Anagram
    LeetCood8:String to Integer
    理解qsort 中的 cmp
    google goble cache
  • 原文地址:https://www.cnblogs.com/tianzeng/p/10248750.html
Copyright © 2020-2023  润新知