数字序列中某一位的数字

题目:

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

链接:剑指offerP225

思路:

寻找规律

以n=1001为例,首先是一位数,有10个(0~9),1001>10,所以肯定不在这10个里面,从后面的数字开始找第1001-10=991位的数字。接着是两位数,有90个(10~99),991>2*90,所以肯定不在这90个数里面,从后面的数字开始找第991-2*90=811位的数字。再接下来是三位数,有900个(100~999),811<3*900,所以肯定在这90个数里面。现在就是找从100开始的第811位的数字,每个数字都是三位,811=3*270+1,因此第811位就是从100开始的第270个数字(370)的中间一位。

规律是先找到第n位的是属于几位数,然后在digit位数中找到对应的那一位数字。

参考代码:

int numberAtIndex(int index)
{
    if(index<0)
        return -1;
    int digit=1;
    while(true)
    {
        int count=countOfDigit(digit);
        if(index<count*digit)
        {
            return numAtIndexDigit(index,digit);
        }
        else
        {
            index=index-count*digit;
            digit++;
        }
    }
}
        

//位数为digit的数字一共多少个,1位数有10个(0~9),2位数有90个(10~99),3位数有900个(100~999)
int countOfDigit(int digit)
{
    if(digit==1)
        return 10;
    int result=9;
    while(digit>1)
    {
        result*=10;
        digit--;
    }
    return result;
}

//在位数为digit的数字中,第index个数字是多少
int numAtIndexDigit(int index,int digit)
{
    int begin=beginOfDigit(digit);
    int temp=begin+index/digit;
    int yu=index%digit;
    for(int i=1;i<digit-yu;i++)
    {
        temp=temp/10;
    }
    return temp%10;
}

//digit位数的第一个数字,如1位数的是0,2位数的是10,3位数的是100
int beginOfDigit(int digit)
{
    if(digit==1)
        return 0;
    int result=1;
    while(digit>1)
    {
        result*=10;
        digit--;
    }
    return result;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值