zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】特殊数题2:44 数字序列中某一位的数字(400. Nth Digit)

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    400. Nth Digit

     
    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.
     
    /*
     
    分析:
    1~9: 9
    10~99:90*2
    100~999:900*3
    */
    #include <cmath>
    class Solution
    {
    public:
        int findNthDigit(int n)
        {
            if(n<0) return 0;
            //计算目标数的位数
            int digits = 1; //单个数的位数
            long base = 9; //某位数的个数 ,为了满足题目n的范围要求,设置为long型
            while(n - base*digits > 0)
            {
                n -= base*digits; //不断减去k位数的个数,直到到目标数的位数
                base*=10;
                digits++; //当前位数
            } //跳出循环时,digits为目标数位数,n为剩余需要计数的总位数
           
            //计算是哪个目标数
            int firstnum = pow(10,digits-1); //当前数位中第一个数,如1、10、100
            int objnum = firstnum;
            int index = n % digits; //index标识要找的数在目标数中哪个位置(从左往右数)
            if(index == 0)  //说明在目标数的最后一位
            {
                index = digits;
                objnum = firstnum + n/digits -1; //注意减1,如100,n = 3,则在100最后一位
            } 
            else
                objnum = firstnum + n/digits; //如 n=4,则在101第一位
           
            //找出是目标数中哪个数字
            for(int i = index; i<digits; i++) objnum/=10; //除到目标位为个位
            return objnum%10;
               
        }
    };
     
  • 相关阅读:
    JavaSE: PrintStream类 和 PrintWriter类
    JavaSE: BufferedWriter类 和 BufferedReader类
    JavaSE: BufferedOutputStream类 和 BufferedInputStream类
    JavaSE: FileOutputStream类 & FileInputSteam类
    MYSQL指令
    用Java GUI做一个简单的管理系统
    [置顶] 用Java GUI做一个简单的管理系统
    HTML5+CSS 静态网页-极米商城
    爬取百度图片
    GhostNet
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10225067.html
Copyright © 2011-2022 走看看