定位数字位数,转化成字符串

  • 注意用long型, 过程结果可能超出int范围。
  • 最后转化成字符串处理。
  • 分辨第n位 前面有n个数字可以被占用,从零开始计算
  • 思路很简单,实现很麻烦
#include <string>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param n int整型 
     * @return int整型
     */
    int findNthDigit(int n) {
        // write code here
        if(n<=9)
        {
            return n;
        }
        int digit=1;
        long n1=n;
        n1=n1-10;
        while(n1>=0)
        {
            digit++;
            n1-=9*pow(10,digit-1)*digit;
        }
        n1+=9*pow(10,digit-1)*digit;
        long index=n1;//3
        long index1=index/digit;//1 //对应的数字从base 以0开始的索引
        int index2=n1-(index1*digit);//1 //相对于最大位的索引;
        long num=index1+pow(10,digit-1);
        string s=to_string(num);

        return s[index2]-'0';

    }
};