This implementation is correct but inefficient.
Code:static int lessThan(int number1, int number2) {
int i = 1;
while (number1 && number2) {
number1 = number1 - 1;
number2 = number2 - 1;
}
if (number1 == 0) {
i = 0;
}
return i;
}
Printable View
This implementation is correct but inefficient.
Code:static int lessThan(int number1, int number2) {
int i = 1;
while (number1 && number2) {
number1 = number1 - 1;
number2 = number2 - 1;
}
if (number1 == 0) {
i = 0;
}
return i;
}
So what's == if it's not a comparison operator?
My mistake, I meant greater-less than operator.
As conjectured in your other topic:
Is this true?Quote:
Originally Posted by Salem
Well... no '<' operator here (hehe)...
Another way to do it, purely in C, but also potentially inneficient (in comparison of using '<'):Code:// Intel/AMD:
int lessThan(int a, int b)
{
int r = 0;
__asm__ __volatile__ (
"cmpl %2,%1\n\t"
"sets %b0"
: "+r" (r) : "r" (a), "g" (b) );
return r;
}
And I agree with Salem... These kinds of exercises are pointless.Code:#include <limits.h>
int lessThan( int a, int b )
{
unsigned int r = a - b;
return ( r >> (sizeof(int) * CHAR_BIT - 1) );
}
I would suggest that you evaluate this question the same way a CPU evaluates this question: do a subtraction, and then look at the resulting number.
A naive approach would be something like:
Tests:Code:is_lt(a, b) // is a less than b?
diff = b - a
if diff is zero, a == b, so return false
if diff is negative, a < b, so return false
if diff is positive, b > a, so return true
- is_lt(4, 0) ? diff = 0 - 4 == -4 -> negative, return false
- is_lt(4, 4) ? diff = 4 - 4 == 0 -> zero, return false
- is_lt(4, 5) ? diff = 5 - 4 == 1 -> positive, return true
More tests:
- is_lt(-100, -101) diff = -101 - -100 == -1 -> negative, return false (whoops!)
- is_lt(100, -101) diff = -101 - 100 == -201 -> negative, return false (ok)
- is_lt(-101, 100) diff = 100 - -101 == 201 -> positive ,return true
So maybe if both are negative you have to switch things around?
How can you test for zero? Seems easy.
How can you test for negative/positive? It turns out this is super easy! Just look up how negative numbers are implemented in 2's-complement arithmetic and you're good to go!
Ahhh... and this works very well:
Right shift with signed integers are "dependent of implementation", accondingly to ISO 9899, due to the fact that most processors implement "logical shifts" and "arithmetic shifts". If a logical shift is used the result will be 1 if a<b or 0, otherwise... if an arithmetic shift is used the result will be -1 if a < b, or 0, otherwise...Code:int lessThan( int a, int b )
{ return (a - b) >> ( sizeof(int) * CHAR_BIT - 1 ); }
Of couse, assuming two's complement are used and msb is the sign bit.