JZ-070-数字序列中的某一位数字

数字序列中的某一位数字

题目描述

数字以 0123456789101112131415... 的格式序列化到一个字符串中,求这个字符串的第 index 位。

题目链接: 数字序列中的某一位数字

代码

/**
 * 标题:数字序列中的某一位数字
 * 题目描述
 * 数字以 0123456789101112131415... 的格式序列化到一个字符串中,求这个字符串的第 index 位。
 */
public class Jz70 {

    public int getDigitAtIndex(int index) {
        if (index < 0) {
            return -1;
        }
        int place = 1;  // 1 表示个位,2 表示 十位...
        while (true) {
            int amount = getAmountOfPlace(place);
            int totalAmount = amount * place;
            if (index < totalAmount) {
                return getDigitAtIndex(index, place);
            }
            index -= totalAmount;
            place++;
        }
    }

    /**
     * place 位数的数字组成的字符串长度
     * 10, 90, 900, ...
     */
    private int getAmountOfPlace(int place) {
        if (place == 1) {
            return 10;
        }
        return (int) Math.pow(10, place - 1) * 9;
    }

    /**
     * place 位数的起始数字
     * 0, 10, 100, ...
     */
    private int getBeginNumberOfPlace(int place) {
        if (place == 1) {
            return 0;
        }
        return (int) Math.pow(10, place - 1);
    }

    /**
     * 在 place 位数组成的字符串中,第 index 个数
     */
    private int getDigitAtIndex(int index, int place) {
        int beginNumber = getBeginNumberOfPlace(place);
        int shiftNumber = index / place;
        String number = (beginNumber + shiftNumber) + "";
        int count = index % place;
        return number.charAt(count) - '0';
    }
}

【每日寄语】 养不教,父之过;教不严,师之惰。

posted @   醉舞经阁  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示