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

数字序列中某一位的数字

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

  1. 要分区间,一位数的,两位数的,0-9,10-99,100-999
  2. 基于区间的起点,定位n在哪个数字
  3. 最后基于求余,找到数字上的具体位置
struct Solution{

}

impl Solution {
    fn new() -> Self {
        Solution{}
    }

    /**
    * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
    *
    * 
        * @param n int整型 
        * @return int整型
    */
    pub fn findNthDigit(&self, n: i32) -> i32 {
        // write code here
          if n < 0 {
        return -1; // or handle the error in your preferred way
    }

    let mut n = n as usize; // Convert n to usize for indexing convenience
    let mut digits_count = 1;
    let mut base = 1;

    // Determine the range of numbers with the given number of digits
    while n > digits_count * 9 * base {
        n -= digits_count * 9 * base;
        digits_count += 1;
        base *= 10;
    }

    // Find the actual number
    let number = base + (n - 1) / digits_count;

    // Find the position of the digit within the number
    let position = (n - 1) % digits_count;

    // Extract the digit
    let digit = number.to_string().chars().nth(position).unwrap();

    digit.to_digit(10).unwrap() as i32
    }
}

#rust#
全部评论

相关推荐

合不合适,我自己说了才算
码农索隆:hr:“真执着啊,来我公司当法人吧”
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 16:15
我应届生,去年10月份开始在这家公司实习,到今年10月份正好一年想(实习+试用期),在想要不要提前9月份就离职,这样好找工作些,但又差一个月满一年,又怕10月份国庆回来离职,容易错过了下半年的金九银十,到年底容易gap到年后
小破站_程序员YT:说这家公司不好吧,你干了快一年 说这家公司好吧,你刚毕业就想跑路说你不懂行情吧,你怕错过金九银十说 你懂行情吧,校招阶段在实习,毕业社招想换工作 哥们,我该怎么劝你留下来呢
应届生,你找到工作了吗
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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