标题的意思解释如下:
如有任意整型数集合A, A={0,2,3 5,1}
求不在A内,且最接近0的数字,明显答案是4;
下面介绍下用程序实现的思路:
A集合用二进制B表示为:B=10 1111,其实5表示从0开始,即占位第六个;
设unsigned X = log(x, B),即X = 5;
B的长度为6,获取掩码C, C=11 1111,即6个1;
设D=C-B=11 1111 - 10 1111 = 01 0000,D即补码;
设E,E为D的反码,即左右颠倒,E=00 0010;
设F = log(2, E),F = 1;
故最接近0的数 = X - F = 4;
/**
* @brief The UniqueIndexSequence class
* 求不在任意整型数集合且最接近0的数
*/
class UniqueIndexSequence {
unsigned d = 0;
public:
/**
* @brief append
* 整形集合添加值
*/
void append(unsigned value);
/**
* @brief niceIndex
* 最接近0的数
*/
unsigned niceIndex();
/**
* @brief invert
* 左右反转,如:0010 0011=》1100 0100
*/
unsigned invert(unsigned value, int len);
};
void UniqueIndexSequence::append(unsigned value)
{
d |= (unsigned)qPow(2, value);
}
unsigned UniqueIndexSequence::niceIndex()
{
//d = 1000, 长度 - 1 = 3
unsigned leng = qLn(d)/qLn(2);
//掩码:1111
unsigned mask = qPow(2, leng + 1) - 1;
//差值:1111 - 1000 = 0111
unsigned xoff = mask - d;
//反转:1110
unsigned vert = invert(xoff, leng);
//定位:1000 -》 3
unsigned retv = qLn(vert)/qLn(2);
//返回值 3 - 3 = 0;
return (leng - retv);
}
unsigned UniqueIndexSequence::invert(unsigned value, int len)
{
unsigned output = 0;
for(int k = 0; k <= len; k ++) {
unsigned din = qPow(2, k);
output |= ((value & din) >> k) << (len - k);
}
return output;
}
20240771
/**
* @brief The lds_sequencenotch class
* 将value按从小到大排序,获取其中的缺口
* 例如:1235031-》4;23045-》1
*/
class lds_sequencenotch
{
public:
void append(int value);
int notch();
void clear();
private:
QMap<int, int> map;
QSet<int> set_value;
};
void lds_sequencenotch::append(int value)
{
int key = value + 1;
int v = map.value(value, -1);
int k = map.key(key, -1);
if(set_value.contains(key))
return;
set_value << key;
if(v != -1 && k != -1) {
map.insert(k, v);
map.remove(value);
} else if(v != -1) {
map.insert(key, map.value(value));
map.remove(value);
} else if(k != -1) {
map.insert(k, value);
} else {
map.insert(key, value);
}
}
int lds_sequencenotch::notch()
{
QList<int> list = map.keys();
if(list.isEmpty())
return 1;
qSort(list);
int d = list.at(0);
int b = map.value(d) - 1;
if(b > 0)
return 1;
return d;
}
void lds_sequencenotch::clear()
{
map.clear();
set_value.clear();
}