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;
               
        }
    };
     
  • 相关阅读:
    Android应用基础概念
    Sqlserver Rand
    sqlite3 锁
    上海盛大网络浩方在线招聘网站程序
    代码片段
    泛型类型的返回
    招 .Net 网站程序员, Flash 程序员
    ACS 20070412 TODO
    MSSQL 2005 分页分析及优化
    虚惊一场
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10225067.html
Copyright © 2011-2022 走看看