@Dave:
without using comparison operator,
int sign = (a >> (sizeof(int) * CHAR_BIT - 1));
sign=0 if a is +ive or 0
else sign=-1;
int mult(int x, int y)
{
int p = 0, s = y;
int sign = (y >> (sizeof(int) * CHAR_BIT - 1));
if(sign) y = add(~y,1);
while(y)
{
if(y & 1) p = add(x, p);
x <<= 1;
y >>= 1;
}
sign=(s>>(sizeof(int)*CHAR_BIT - 1));
if(sign) p = add(~p,1);
return(p);
}
On Sat, May 14, 2011 at 2:28 AM, Dave <[email protected]> wrote:
> @Ashish: Here's addition, subtraction, and multiplication with bit
> manipulation and comparisons. I doubt if you can do them without
> comparisons.
>
> int add(int x, int y)
> {
> int c;
> while(y)
> {
> c = x & y;
> x ^= y;
> y = c << 1;
> }
> return(x);
> }
>
> int sub(int x, int y)
> {
> return(add(x,add(~y,1));
> }
>
> int mult(int x, int y)
> {
> int p = 0, s = y;
> if(y < 0) y = add(~y,1);
> while(y)
> {
> if(y & 1) p = add(x, p);
> x <<= 1;
> y >>= 1;
> }
> if(s < 0) p = add(~p,1);
> return(p);
> }
>
> Dave
>
> On May 12, 10:03 pm, Ashish Goel <[email protected]> wrote:
> > Using bit manipulation, implement add, subtract and multiply on two
> > integers. You cannot use any arithmetic operations, such as +, - or *.
> >
> > Best Regards
> > Ashish Goel
> > "Think positive and find fuel in failure"
> > +919985813081
> > +919966006652
>
> --
> You received this message because you are subscribed to the Google Groups
> "Algorithm Geeks" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to
> [email protected].
> For more options, visit this group at
> http://groups.google.com/group/algogeeks?hl=en.
>
>
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.