C++版 - Leetcode 400. Nth Digit解题报告 编辑

leetcode 400. Nth Digit

在线提交网址: https://leetcode.com/problems/nth-digit/

  • Total Accepted: 4356
  • Total Submissions: 14245
  • Difficulty: Easy

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …

Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).

Example 1:

Input:
3

Output:
3

Example 2:

Input:
11

Output:
0

Explanation:

The 11th digit of the sequence `1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...` is a 0, which is part of the number 10.

Tags: Math

分析:

1.1位数共有9=9·1个, 1~9;

2.2位数共有90=9·10个, 10~99;

3.3位数共有900=9·10·10个, 100~999;

已AC代码:

#include<cstdio>
#include<iostream>
using namespace std;

class Solution {
    public:
        int findNthDigit(int n) {
            int len = 1, base = 1;  // len表示当前数的位数, base表示当前位是个位、百位、千位等...
            while (n > 9L * base * len) {
                n -= 9 * base * len;
                len++;
                base *= 10;
            }
            int curNum = (n - 1)/len + base, digit = 0;   // curNum是含有所找digit的那个数
            for (int i = (n - 1) % len; i < len; ++i) {          // 根据偏移量找到所找的数字
                digit = curNum % 10;
                curNum /= 10;
            }
            return digit;
        }
};
// 以下为测试 
int main() {
    Solution sol;
    int n;
    cin>>n;  // 150
    int res = sol.findNthDigit(n);
    cout<<res<<" "<<endl;
    return 0;
}


作者:极客玩家
出处:https://geekzl.com

如果,您希望更容易地发现我的新文章,不妨点击一下绿色通道的关注我,亦可微信搜索公众号大白技术控关注我。

如果您觉得阅读本文对您有帮助,请点击一下右下方的推荐按钮,您的推荐将是我写作的最大动力!
版权声明:本文为博主原创或转载文章,欢迎转载,但转载文章之后必须在文章页面明显位置注明出处,否则保留追究法律责任的权利。如您有任何疑问或者授权方面的协商,请          .
posted @   大白技术控  阅读(233)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

打赏

>>

欢迎打赏支持我 ^_^

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示