Hello I am trying to write a function for my lab which requires me to inverse a positive number with restricted operators. The operators allowed are: ! ~ & ^ | + << >>
My initial approach was to double x using addition: x + x and then subtracting that from x to get the inverse, but was roadblocked due to the operator restrictions. I am rather new to C and trying to learn, if someone could provide me with the ideology behind performing this operation I would greatly appreciate it.
Here is the classic solution you are probably expected to produce:
int negate_positive_number(int n) {
return ~n + 1;
}
The problem with this code is it only works on 2's complement systems. This is not a real issue as you are probably not going to encounter other architectures today.
Yet the C Standard supports other representations for signed integers:
In both of these historical oddities, there are 2 possible representations for 0
, one of which could be a trap value.
Here is an original solution that works for all 3 architectures: 2's complement, sign/magnitude and ones' complement systems: a bit obscure but more portable:
#include <limits.h>
int negate_positive_number(int n) {
return (n ^ INT_MIN ^ INT_MAX) + (1 & (INT_MIN + INT_MAX));
}
It uses +
, ^
and &
and the definitions from <limits.h>
, which might be off limits. I assume parentheses are allowed too.
Collected from the Internet
Please contact debug[email protected] to delete if infringement.
Comments