zoukankan      html  css  js  c++  java
  • 剑指offer-面试题44-数字序列中某一位的数字-脑筋急转弯

    /*
    题目:
    	数字以0123456789101112131415…的格式序列化到一个字符序列中。
    	在这个序列中,第5位(从0开始计数,即从第0位开始)是5,第13位是1,第19位是4,等等。
    	请写一个函数,求任意第n位对应的数字。
    */
    
    #include<iostream>
    #include<string.h>
    
    using namespace std;
    
    //自己实现pow,使用codeblocks中的pow,会转化为浮点数进行截断,得到的结果不准确。
    int pow(int num,int digits){
    
        int res = 1;
        for(int i = 0; i < digits; i++){
            res *= num;
        }
        return res;
    }
    /*
    解法一:
    	一个数字一个数字遍历,当数字位数之和超过n,则所需数字在遍历到的最后一个数字。
    */
    int NumberOfSequence1(int n){
        if(n < 0) return -1;
        int currNumber = 0;
        int myCount = 0;
        while(myCount <= n){
            myCount += to_string(currNumber).size();
            currNumber++;
        }
        return to_string(currNumber-1)[n-myCount+to_string(currNumber-1).size()] -'0';
    }
    
    /*
    解法二:
    	0~9中有10个数,10~99有2*90=180个数,100~999有3*900=2700个数
    	例1001,可以有10+180<1001 && 10+180+2700>1001,所以要找的数在100~999中
    	1001-10-180=881,881/3=270,881%3=1,所以要找的数在100+270=370中
    	其中截止到369有810个数字,3为第811个数字,7为第812个数字,0为813个数字
    	从0开始计数,则7为811位数字。
    */
    int NumberOfSequence2(int n){
        if(n < 0) return -1;
        if(n < 9) return n;
    
        int myCount = 10;
        int i = 2;
        while(myCount <= n){
            myCount = myCount + (int)i*9*pow(10,i-1);
            i++;
        }
        int temp = n - (myCount - (i-1)*9*pow(10,i-2));
        int res_index= temp%(i-1);
        int res_val = (temp / (i - 1) + pow(10,i-2));
    
        return to_string(res_val)[res_index] - '0';
    }
    
    
    
    
    int main(){
        cout<<NumberOfSequence2(1500000)<<endl;
        cout<<NumberOfSequence1(1500000)<<endl;
    }
    

       

  • 相关阅读:
    [kuangbin带你飞]专题十二 基础DP1 E
    hdu 1203 I NEED A OFFER! (01背包)
    hdu 2602 Bone Collector (01背包)
    hdu 4513 吉哥系列故事——完美队形II (manacher)
    hdu 2203 亲和串 (KMP)
    hdu 1686 Oulipo (KMP)
    hdu 1251 统计难题 (字典树)
    hdu 2846 Repository (字典树)
    hdu 1711 Number Sequence (KMP)
    poj 3461 Oulipo(KMP)
  • 原文地址:https://www.cnblogs.com/buaaZhhx/p/12019287.html
Copyright © 2011-2022 走看看