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.

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.

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

ReplyDeleteany other logic?

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

ReplyDelete@anonymous: a is the given integer.

ReplyDeleteit 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.

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

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

ReplyDeleteit should be ...

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

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

(a>0)||(a=-a)

ReplyDelete