This is a list on the solutions I got from various people on the C riddle, that m3ntor brought up on #demo-gr a couple of days ago.
The riddle goes like this: increment an unsigned int by one in C, without using any of the operators +, -, ++, --, +=, -=, and without any library function calls.
| person | solution |
|---|---|
| m3ntor and samurai |
unsigned int num; num = ~num * 0xffffffff; |
| Nuclear |
unsigned int num; num = &((char*)num)[1]; |
| imak |
unsigned int num; unsigned int w=1, t=num; while((t^=w)<num)w<<= 1; num=t; |
| xtapodi_kataifi |
unsigned int num;
unsigned int y = 1;
while(num & y) {
num = num ^ y;
y = y << 1;
}
num = num | y;
|
| Bartosz Dobrzeleck |
unsigned int inc(unsigned int num)
{
unsigned int k = 1, l;
while(k <= num) {
if((k & num) == 0) {
l=k;
while(l > 1) {
num >>= 1;
l >>= 1;
}
l=k;
while(l > 1) {
num <<= 1;
l >>= 1;
}
num |= k;
return num;
}
k <<= 1;
}
return k;
}
|