题目描述如下:
从1开始的整数数列 1, 3, 5, 6, 7, 8, 9, 10, 11, 13, 15 ...
其中不能含有2和4,比如2,4, 12, 14, 20, 21, 40, 124... 等都不能在数列中。
求第N个数是几? 要求时间复杂度为 O(1)。
(不需要考虑超出int范围的问题)
比如:N=5, 输出7; N=50, 输出83;
要求时间复杂度为 O(1)。 所以从1开始挨个遍历的不符合要求。
直接给出思路:用8进制!
组成8进制的8个数字分别为:[0, 1, 3, 5, 6, 7, 8, 9]。
如果要求第50个数是几,N=50,用8进制表示为62,在我们的8进制中,6应该是8,2应该是3.所以N=50时,输出83.
代码如下:
#include <stdio.h>
int myPower(int base, int power)
{
int i = 0;
int result = 1;
for (i = 0; i < power; i++)
{
result *= base;
}
return result;
}
int isContainNumber(int base, int number)
{
int quotion = base;
int remainder = 0;
while (quotion > 0)
{
remainder = quotion % 10; //十进制
if (number == remainder)
{
return 1;
}
quotion = quotion / 10;
}
return 0;
}
int main(int argc, char* argv[])
{
int N = 0;
int quotion = 0;
int remainder = 0;
int result = 0;
int count = 0;
int array[8] = {0, 1, 3, 5, 6, 7, 8, 9};
printf("please input N : ");
scanf("%d", &N);
/** 8 进制思想---------------方法1 */
quotion = N;
while (quotion > 0)
{
remainder = quotion % 8;
result += (array[remainder] * myPower(10, count));
quotion = quotion / 8;
count++;
}
printf("the number is %d \n", result);
/** 对比验证程序----------方法2 */
count = 0;
int i = 0;
while (count < N)
{
i++;
if (1==isContainNumber(i, 2) || 1==isContainNumber(i, 4))
{
}
else
{
count++;
}
}
printf("the number is %d \n", i);
return 0;
}