题解 | #数字序列中某一位的数字#

数字序列中某一位的数字

http://www.nowcoder.com/practice/29311ff7404d44e0b07077f4201418f5

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param n int整型 
     * @return int整型
     */
    int findNthDigit(int n) {
        // write code here
        if(n < 10)
            return n;
        int start = 1;
        int end = 10;
        long long bit = 1;
        //找到对应的区间
        while((long long)n >= (end - start)*bit){
            //减去之前的位数
            n =  n - (end - start)*bit;
            //区间头
            start *= 10;
            //区间尾
            end *= 10;
            
            //位数++
            ++bit;
            
        }
        //找到当前数
        string res = to_string(start + (n-1)/bit);
       //返回对应的数字
        return res[(n-1)%bit] - '0';
    }
};

**参考资料链接:https://leetcode-cn.com/problems/nth-digit/solution/shu-xue-by-wanglongjiang-h9n4/**

全部评论

相关推荐

龙珠传说:nb,公务员解约不需要支付违约金吧
点赞 评论 收藏
分享
06-23 11:43
门头沟学院 Java
allin校招的烤冷...:我靠,今天中午我也是这个hr隔一个星期发消息给我。问的问题还是一模一样的😅
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务