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 inc(unsigned int num) { return ~num * 0xffffffff; } |
Nuclear |
unsigned int inc(unsigned int num) { return &((char*)num)[1]; } |
imak |
unsigned int inc(unsigned int num) { unsigned int w=1, t=num; while((t^=w)<num)w<<= 1; return t; } |
imak take 2 |
unsigned int inc(unsigned int num) { unsigned int a = 0x40000000|(((unsigned int)num)<<23); float b = (*((float*)(&a)))*2.0f; return (*((unsigned int*)&b)^0x40000000)>>23; } |
xtapodi_kataifi |
unsigned int inc(unsigned int num) { unsigned int y = 1; while(num & y) { num = num ^ y; y = y << 1; } return 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; } |
Peter Simons |
int inc(int i) { return (i&1) == 0 ? i | 1 : inc((unsigned int)i >> 1) << 1; } |