Dan*_*Dan 7 c++ algorithm optimization
简单的问题 - 在c ++中,获得两个数字(u0和u1)中哪一个是最小正数的最佳方法是什么?(那仍然有效)
我尝试的每一种方式都涉及大的if语句或复杂的条件语句.
谢谢,丹
这是一个简单的例子:
bool lowestPositive(int a, int b, int& result)
{
//checking code
result = b;
return true;
}
lowestPositive(5, 6, result);
Run Code Online (Sandbox Code Playgroud)
Dou*_*rie 15
如果值以二进制补码表示,那么
result = ((unsigned )a < (unsigned )b) ? a : b;
Run Code Online (Sandbox Code Playgroud)
将起作用,因为二进制补码中的负值在被视为无符号时比正值更大.与杰夫的答案一样,这假设至少有一个值为正值.
return result >= 0;
Run Code Online (Sandbox Code Playgroud)
tva*_*son 12
我更喜欢清晰度而非紧凑性:
bool lowestPositive( int a, int b, int& result )
{
if (a > 0 && a <= b) // a is positive and smaller than or equal to b
result = a;
else if (b > 0) // b is positive and either smaller than a or a is negative
result = b;
else
result = a; // at least b is negative, we might not have an answer
return result > 0; // zero is not positive
}
Run Code Online (Sandbox Code Playgroud)