Project Euler #40: Champernowne's constant (C++)

Question
An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expression.
d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000

Answer :

Hacker Rank Problem

Solution


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <string>
#include <iostream>

unsigned int getDigit(unsigned long long pos)
{
    unsigned int       digits = 1;
    unsigned long long range  = 9;
    unsigned long long first  = 1;
    unsigned long long skip = 0;
    while (skip + digits*range < pos)
    {
        skip += digits*range;
        digits++;
        range *= 10;
        first *= 10;
    }

    while (range > 9)
    {
        while (skip + digits*range < pos)
        {
            skip  += digits*range;
            first += range;
        }
        range /= 10;
    }

    while (skip + digits < pos)
    {
        first++;
        skip += digits;
    }

    pos -= skip;
    pos--;

    auto s = std::to_string(first);
    return s[pos] - '0';
}

int main()
{
    unsigned int tests;
    std::cin >> tests;
    while (tests--)
    {
        unsigned int product = 1;
        for (unsigned int i = 0; i < 7; i++)
        {
            unsigned long long pos;
            std::cin >> pos;
            product *= getDigit(pos);
        }
        std::cout << product << std::endl;
    }

    return 0;
}

Comments

Popular Posts