M
Method Man
Q:
Write a C/C++ program that takes an unsigned integer and adds 1 to it
without using the plus or minus signs. Don't worry about overflow issues. It
is cheating to use assembly commands, or to write a preprocessor that uses
ASCII codes to insert the plus or minus sign. There are many solutions, some
more elegant than others.
Here's the solution I came up with. I'm wondering if there's a solution that
is more elegant or efficient.
void addOne(unsigned int &i) {
int j = 1;
while (i & 1) {
i >>= 1;
j <<= 1;
}
i |= 1;
while !(j & 1) {
i <<= 1;
j >>= 1;
}
}
Write a C/C++ program that takes an unsigned integer and adds 1 to it
without using the plus or minus signs. Don't worry about overflow issues. It
is cheating to use assembly commands, or to write a preprocessor that uses
ASCII codes to insert the plus or minus sign. There are many solutions, some
more elegant than others.
Here's the solution I came up with. I'm wondering if there's a solution that
is more elegant or efficient.
void addOne(unsigned int &i) {
int j = 1;
while (i & 1) {
i >>= 1;
j <<= 1;
}
i |= 1;
while !(j & 1) {
i <<= 1;
j >>= 1;
}
}