查找元素是否在指定数组中
Finding if element is within a specified Array
我正在尝试查找 ptr 是否指向指定 intArray 中的元素。 return 真则为 1,假则为 0。
请看代码。
int withinArray(int * intArray, int size, int * ptr) {
int length = ptr - intArray;
int signal = length >> 31;
//size
int size1 = (size - 1 - length) >> 31;
return (signal | size1) + 1;
}
程序有效。但是,我不允许使用二进制整数运算符:&、&&、|、||、<、>、!=、/、% 或一元运算符:~ 或指针运算符:[]。到目前为止,我的解决方案要求我使用 |符号(参见 return 语句)。无论如何我可以解决这个问题吗?我尝试了其他几种方法,所有方法都包括 |或 & 符号,这是不允许的。我已经坚持了一段时间了,想不出解决这个问题的方法。
OP 的代码依赖于未定义的行为 (UB)。
指针减法 ptr - intArray
如果 ptr
不在数组中(或一次传递结束)则为 UB。
代码一次可以再次比较每个元素。效率低,但不是UB。
也许:
// not allowed to use the Binary integer operators:&, &&, |, ||, <, >, !=, /, % or Unary: ~
int withinArray(int * intArray, int size, int * ptr) {
while (size >= 1) {
// Unclear if ==, ++ this counts for OP as a "Pointer operator"
if (intArray == ptr) return 1;
intArray++;
size--;
}
return 0;
}
如果可用,代码可以尝试将指针转换为足够范围的整数(指针可以很容易地超过 32 位 int
甚至 64 位),然后尝试一个整数 computation/compare。然而,即使这样也不可移植,因为转换为 2 个不同整数的 2 个指针可能仍指向具有非线性地址模型的相同地址。
我知道您不能使用运算符:&、&&、|、||、<、>、!=、/、% 或一元运算符:~ 或指针运算符:[].
但是你可以使用==运算符吗?如果是,那么以下解决方案将适合您。
int withinArray(int * intArray, int size, int * ptr) {
while(size--) {
if(intArray == ptr) return 1;
intArray++;
}
return 0;
}
希望对您有所帮助:)
我正在尝试查找 ptr 是否指向指定 intArray 中的元素。 return 真则为 1,假则为 0。
请看代码。
int withinArray(int * intArray, int size, int * ptr) {
int length = ptr - intArray;
int signal = length >> 31;
//size
int size1 = (size - 1 - length) >> 31;
return (signal | size1) + 1;
}
程序有效。但是,我不允许使用二进制整数运算符:&、&&、|、||、<、>、!=、/、% 或一元运算符:~ 或指针运算符:[]。到目前为止,我的解决方案要求我使用 |符号(参见 return 语句)。无论如何我可以解决这个问题吗?我尝试了其他几种方法,所有方法都包括 |或 & 符号,这是不允许的。我已经坚持了一段时间了,想不出解决这个问题的方法。
OP 的代码依赖于未定义的行为 (UB)。
指针减法 ptr - intArray
如果 ptr
不在数组中(或一次传递结束)则为 UB。
代码一次可以再次比较每个元素。效率低,但不是UB。
也许:
// not allowed to use the Binary integer operators:&, &&, |, ||, <, >, !=, /, % or Unary: ~
int withinArray(int * intArray, int size, int * ptr) {
while (size >= 1) {
// Unclear if ==, ++ this counts for OP as a "Pointer operator"
if (intArray == ptr) return 1;
intArray++;
size--;
}
return 0;
}
如果可用,代码可以尝试将指针转换为足够范围的整数(指针可以很容易地超过 32 位 int
甚至 64 位),然后尝试一个整数 computation/compare。然而,即使这样也不可移植,因为转换为 2 个不同整数的 2 个指针可能仍指向具有非线性地址模型的相同地址。
我知道您不能使用运算符:&、&&、|、||、<、>、!=、/、% 或一元运算符:~ 或指针运算符:[].
但是你可以使用==运算符吗?如果是,那么以下解决方案将适合您。
int withinArray(int * intArray, int size, int * ptr) {
while(size--) {
if(intArray == ptr) return 1;
intArray++;
}
return 0;
}
希望对您有所帮助:)