You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在无数组情况下获取重复数字序列指定位置的数字

解决方案

核心思路

要找到序列中第P位的数字,无需生成整个序列(也不需要数组),可以通过逐步减去每个数字贡献的总位数来定位目标数字:

  1. 从数字1开始,依次计算每个数字n贡献的总位数:
    • 若n是1-9的个位数,总位数为n * 1(每个n重复n次,每次1位)
    • 若n是10-99的两位数,总位数为n * 2(每个n重复n次,每次2位)
  2. 比较P与当前数字的总位数:
    • 若P大于该总位数,将P减去这个总位数,继续下一个数字
    • 若P小于等于该总位数,说明目标数字就在当前n的重复序列中
  3. 定位到具体数字后,再确定是n的哪一位:
    • 个位数直接输出n即可
    • 两位数通过计算(P-1)%2判断是十位还是个位(0为十位,1为个位)

修改后的完整代码

#include <stdio.h>
#include <stdlib.h>

int main()
{
    system("chcp 1251");
    printf("\n");
    const int Num_Max = 99;
    int P, number = 0;

    // 可选:打印整个序列(注:序列很长,建议测试时注释掉)
    printf("Series of number: ");
    for (int i = 0; i <= Num_Max; i++)
    {
        for (int j = 0; j < i; j++)
        {
            printf("%d", number);
        }
        number++;
    }
    printf("\n\n");

    // 获取并验证输入的位置P
    printf("Enter the position: ");
    scanf_s("%d", &P);
    while (P < 1 || P > 2500)
    {
        printf("Another number: ");
        scanf_s("%d", &P);
    }
    printf("Chosen position: %d\n", P);

    // 计算第P位的数字
    int n = 1;
    while (1)
    {
        int digits_per = (n < 10) ? 1 : 2;
        int total_digits = n * digits_per;
        if (P > total_digits)
        {
            P -= total_digits;
            n++;
        }
        else
        {
            break;
        }
    }

    char target_digit;
    if (n < 10)
    {
        target_digit = '0' + n;
    }
    else
    {
        int digit_pos = (P - 1) % 2;
        if (digit_pos == 0)
        {
            target_digit = '0' + (n / 10); // 取十位
        }
        else
        {
            target_digit = '0' + (n % 10); // 取个位
        }
    }

    printf("The digit at position %d is: %c\n", P, target_digit);

    return 0;
}

代码说明

  1. 输入验证:简化原代码的判断逻辑,用单个while循环统一处理非法输入
  2. 数字定位循环:通过逐步减去每个数字的总位数,快速锁定包含目标位置的数字n
  3. 位数提取:
    • 个位数直接转换为字符输出
    • 两位数通过模运算确定是十位还是个位,再提取对应数字转换为字符

内容的提问来源于stack exchange,提问作者Nikita Ivankov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 13:01:13