Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Increment unsigned int by 1 using bit-shifting & logical opr only?

I have a question in my assignment / project that adds 1 to an unsigned integer only using bit-shifting and logical operators. There shouldn't be any "+", "-", "*", or "/" symbols in the function.

I am trying from last days but no success yet. So far I've tried the following:

int A = (((B&C)<<1)^(B^C))

Can anybody help me to solve this.?

You can help me in any programming language.

like image 255
MicroEyes Avatar asked Nov 28 '22 21:11

MicroEyes


2 Answers

unsigned int i = ...;
unsigned int mask = 1;
while (i & mask)
{
    i &= ~mask;
    mask <<= 1;
}
i |= mask;
like image 167
Henrik Avatar answered Dec 04 '22 23:12

Henrik


Java:

public static int inc(int i){
        if ((i & 1) == 0)
            return i | 1;
        else 
            return inc(i>>1)<<1;
    }

P.S. while loop variant by henrik is obviously faster

like image 45
gkuzmin Avatar answered Dec 04 '22 22:12

gkuzmin