Problem
Find two's compliment of a negative number. Code it.
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Find two's compliment of a negative number.
Created Date : 4-July-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <iomanip>
#include <limits>
#include <cassert>
using namespace std;
static void ComputeNegativeComplimentProcess(int num)
{
assert(num < 0);
cout << num << endl;
char buffer[256];
itoa(-num, buffer, 2);
cout << setw(32) << buffer << endl;
itoa(~(-num), buffer, 2);
cout << setw(32) << buffer;
cout << " -- One's compliments" << endl;
itoa(~(-num) + 1, buffer, 2);
cout << setw(32) << buffer;
cout << " -- Two's compliments" << endl;
cout << "-------------------------------" << endl;
}
int main(int argc, char* argv[])
{
for (int i = 31; i >= 0; --i)
{
if (i % 10 == 0)
{
cout << i / 10;
}
else
{
cout << " ";
}
}
cout << endl;
for (int i = 31; i >= 0; --i)
{
cout << i % 10;
}
cout << endl;
for (int i = -10; i < 0; ++i)
{
ComputeNegativeComplimentProcess(i);
}
return 0;
}
Output
3 2 1 0
10987654321098765432109876543210
-10
1010
11111111111111111111111111110101 -- One's compliments
11111111111111111111111111110110 -- Two's compliments
-------------------------------
-9
1001
11111111111111111111111111110110 -- One's compliments
11111111111111111111111111110111 -- Two's compliments
-------------------------------
-8
1000
11111111111111111111111111110111 -- One's compliments
11111111111111111111111111111000 -- Two's compliments
-------------------------------
-7
111
11111111111111111111111111111000 -- One's compliments
11111111111111111111111111111001 -- Two's compliments
-------------------------------
-6
110
11111111111111111111111111111001 -- One's compliments
11111111111111111111111111111010 -- Two's compliments
-------------------------------
-5
101
11111111111111111111111111111010 -- One's compliments
11111111111111111111111111111011 -- Two's compliments
-------------------------------
-4
100
11111111111111111111111111111011 -- One's compliments
11111111111111111111111111111100 -- Two's compliments
-------------------------------
-3
11
11111111111111111111111111111100 -- One's compliments
11111111111111111111111111111101 -- Two's compliments
-------------------------------
-2
10
11111111111111111111111111111101 -- One's compliments
11111111111111111111111111111110 -- Two's compliments
-------------------------------
-1
1
11111111111111111111111111111110 -- One's compliments
11111111111111111111111111111111 -- Two's compliments
-------------------------------
Press any key to continue . . .