Monday, March 28, 2011

Find the absolute value of an integer

Given an integer find the absolute value without using conditional statements

Approach:
The last bit (31st bit in case of 4 byte variable) contains the sign information. If you update the value of the 31st bit, the job is done.

7 comments :

  1. (a&(1<<31))&&(a=~a+1)

    any other logic?

    ReplyDelete
  2. (a&(1<<31)) gives 0 for all a not equal to 0, when MSB of a isn't 1 .. gives absolute value 0 ..

    ReplyDelete
  3. @anonymous: a is the given integer.

    it is nothing but:-

    (a&(1<<31))&&(a=-a)...the right side of && is executed only in case of negative integers...and a is set to positive value.

    ReplyDelete
  4. and if a is positive then how it can be found out ?

    ReplyDelete
  5. if a is positive, nothing happens to the value of a as required...better use it in a program.

    ReplyDelete
  6. it should be ...

    unsigned b = (a&(1<<31)) && ( (~a)+1 );

    printf("\n abs of %d = %u\n\n",a, a-b*2*a);

    ReplyDelete