C/C++, Codes

Calculating the Absolute value of an Integer

I collected some idea of my own and from the internet on the fast way to calculate the Absolute value of an integer.

Theory :
The Absolute value(Abs) of an integer X is :
X if X\textgreater 0
-X if X \textless 0
Abs(0) = 0;

Nothing Special! This is my simple and easy approach :

#include <iostream>
using namespace std;

int Abs1(int);

int main()
{
	int n;
	cout << "Enter a number : ";
        cin  >> n;

        //As simple as the theory
	if (n > 0)
         cout << "+" << n;
        else if (x == 0) cout << 0;
             else cout "-" << n;

	return 0;
}

Another cool approach:
Note : if we plus X with the negative of double X we get the negative X, or:
Abs(x < 0) = x + x*(-2);

#include <iostream>
using namespace std;

int Abs(int);

int main()
{
	int n;
	cout << "Enter a number : ";
        cin  >> n;
	cout << Abs(n);

        return 0;
}

int Abs(int x) {
   if (x > 0) return x;

   //this can calculate out the negative value of x
   return x + x*(-2);
}

Source : http://diendan.congdongcviet.com/showpost.php?p=154426&postcount=4.

Another great approach :


int Abs ( int x )
{
 if ( x > 0 ) return x ;

//flip all the bit and add one
 return ~x + 1 ;
}

The reason why this way is better is becuase of its not using multiplication. The computer does operation on the “+” is faster than mulltiplier. In fact, “+” is the only operation that the computer know how to operate. Moreover, this solution has taken use of the advantage of two complement notation, which we can convert a positive number into negative by flipping all the bit and add one. For example :

BINARY(DEC)

*         *         *
012345678901234567890123456789012

000000000000000000000000000000001 (1)

111111111111111111111111111111110 (4294967294) [Flip all the bits]

+                               1
– – – – – – – – – – – – – – – – – – – – – — – – – – – – – – —

111111111111111111111111111111111 (4294967295) [MAX INT]

Source : http://diendan.congdongcviet.com/showpost.php?p=154435&postcount=11 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s