Pregunta de entrevista de Two Sigma

Bitwise Operation, Add one to a number without using +

Respuestas de entrevistas

Anónimo

25 de nov de 2015

int add (int n) { return n & 1 ? add (n>>1)<<1 : n | 1; } First expression in the ternary operator is carrying the 1 if the last binary digit is one, the second is adding the 1 if the last binary digit is 0

4

Anónimo

27 de nov de 2017

-(~x)

1

Anónimo

24 de nov de 2015

#include #include using namespace std; int AddOne(int N); int main() { srand(0); int N = 0; for (int i=0; i0) { Temp = (CarryIn & N) & One[bitI++]; N = (N ^ CarryIn); CarryIn = Temp << 1; } return N; } Ironically, although the "+" is not applied to the number, the iteration index is incremented.