Cod: Selectaţi tot
#include <iostream>
#include <string>
#include <cmath>
char invert(char digit)
{
if(digit == '1')
return '2';
else
return '1';
}
char _getDigit(int index, int k, std::string base)
{
// We have reached the base string (1221)
if(k == 1)
{
// -1 since string index starts at 0
return base[index - 1];
}
const int subSequenceLength = pow(4.0, k - 1);
// how many subdivisions of the main sequence it fully covers
int repetition = index / subSequenceLength ;
int innerI; // this is n'
if(index % subSequenceLength == 0)
{
innerI = 4; // it is the last digit i the last fully coverd subsequence
}
else
{
innerI = index % subSequenceLength;
// we increment it since we have one sequence that we haven't fully
// coverd.
repetition++;
}
char result = _getDigit(innerI, k - 1, base);
if(repetition == 2 || repetition == 3)
return invert(result);
return result;
}
char getDigit(int index, std::string base)
{
int k = 1;
for(int i = 4; i < index; k++, i *= 4)
;
return _getDigit(index, k, base);
}
int main()
{
int digitIndex;
std::cout << "Insert n: ";
std::cin >> digitIndex;
std::cout << std::endl;
std::cout << "The digit is " << getDigit(digitIndex, "1221") << std::endl;
return 0;
}