hihocoder上第180周《Nature Numbers》

来源:互联网 发布:php 断点续传 编辑:程序博客网 时间:2024/05/29 18:21

原题链接:http://hihocoder.com/contest/hiho180/problems

描述

Consider the following sequence S which is constrcuted by writting nature numbers one by one: “012345678910111213…”.

The first digit of S, S[0], is 0. The second digit S[1] is 1. And the 11th digit S[10] is 1.

Given an integer N, can you find the digit S[N]?

输入
An integer N. (0 <= N <= 1018)

输出
Digit S[N].

样例输入
17
样例输出
3

Solution:

本题属于数学问题,可以按照每一个数的位数来加快计算,例如,个位数有10,2位数90,3位数900,依次类推即可。代码如下:
#include <iostream>#include <cmath>using namespace std;typedef long long ll;int main() {    ll N;    while (cin >> N) {        ll n = N;           // 剩余位数        ll k = 1;           // 几位数        ll nums = 10;       // 该k位数有多少个        while (n - k * nums >= 0) {            n -= k * nums;            k++;            if (k == 2) nums *= 9;            else nums *= 10;        }        ll m = k == 1 ? 0 : pow(10, k - 1); // k位数的起始数        ll nn = n / k + m;      // 第N个字符所在数的大小        ll mm = n % k;          // 第几位        cout << (nn % ll(pow(10, k - mm)))             / ll(pow(10, k - mm - 1)) << endl;    }}
原创粉丝点击