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

浪尽此生 提交于 2019-12-04 17:03:55
unsigned int i = ...;
unsigned int mask = 1;
while (i & mask)
{
    i &= ~mask;
    mask <<= 1;
}
i |= mask;
gkuzmin

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

Logic to inrement a number without using arithmetic operators(+, -. * and /)

unsinged int no = 3; //actual number
unsigned int one = 1;
unsigned int ans = 0;
unsigned int carry = 0;
unsigned int prev_ans = 0;
unsigned int prev_carry = 0;

ans = no ^ one;
carry = no & one;

while (carry != 0)
{
   carry <<= 1;

   prev_ans = ans;
   prev_carry = carry;

   ans = prev_ans ^ prev_carry;
   carry = prev_ans & prev_carry;
}

Google for Full Adder and try to implement one.

This is too easy, for example in Haskell:

data Unsigned = Zero | Succ Unsigned
increment :: Unsigned -> Unsigned
increment u = Succ u

No bitwise or arithmetic operators, no operators at all!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!