zoukankan      html  css  js  c++  java
  • 剑指offer44 数字序列中某一位的数字

    package com.example.lettcode.offer;
    
    /**
     * @Class FindNthDigit
     * @Description 剑指offer44 数字序列中某一位的数字
     * 数字以0123456789101112131415…的格式序列化到一个字符序列中。
     * 在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
     * 请写一个函数,求任意第n位对应的数字。
     * 示例 1:
     * 输入:n = 3
     * 输出:3
     * <p>
     * 示例 2:
     * 输入:n = 11
     * 输出:0
     * <p>
     * 限制:
     * 0 <= n < 2^31
     * @Author
     * @Date 2020/7/20
     **/
    public class FindNthDigit {   
    }
    
    /**
     * 解法:
     * 1. 确定n所在数字的位数,记为digit;
     * 2. 确定n所在的数字,记为num;
     * 3. 确定n是num中的哪一数位,并返回结果。
     */
    public static int findNthDigit(int n) {
    
            int digit = 1;      // n所在数字的位数
            long start = 1;     // 相同位数数字的第一个数字
            long count = 9;
            // 确定n所在数字的位数,记为digit;
            while (n > count) { // 1.
                n -= count;
                digit += 1;
                start *= 10;
                count = digit * start * 9;
            }
            // 确定n所在的数字,记为num;
            long num = start + (n - 1) / digit; // 2.
            return Long.toString(num).charAt((n - 1) % digit) - '0'; // 3.
        }
    
    // 测试用例
    public static void main(String[] args) {
    	int n = 3;
    	int ans = findNthDigit(n);
    	System.out.println("FindNthDigit demo01 result:" + ans);
    
    	n = 11;
    	ans = findNthDigit(n);
    	System.out.println("FindNthDigit demo01 result:" + ans);
    
    	n = 120;
    	ans = findNthDigit(n);
    	System.out.println("FindNthDigit demo01 result:" + ans);
    
    	n = 1200;
    	ans = findNthDigit(n);
    	System.out.println("FindNthDigit demo01 result:" + ans);
    }
    
  • 相关阅读:
    做代码的曲线问题
    全书目录
    关于《Delphi源代码分析》的讨论
    说说“从编程到工程”专栏的由来
    CF285E Positions in Permutations
    CF264B Good Sequences
    CF115E Linear Kingdom Races
    CF633F The Chocolate Spree
    CF767C Garland
    CF559C Gerald and Giant Ches
  • 原文地址:https://www.cnblogs.com/fyusac/p/13346303.html
Copyright © 2011-2022 走看看