This was a program given to me in an interview unfortunately I was not able to complete it in very short time hence I am writing this code here so that this may help any one ;-)
C++ Source :
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
int GetIntegerComplement(int nInputNum)
{
int nRemider = 0, nCompRem = 0, nSum = 0, nCompSum=0, nTempNum;
int nPos=1;
string strComp="";
char ChArray[2];
size_t Size = 1;
nTempNum = nInputNum;
do
{
nRemider = nTempNum % 2;
if (nRemider == 0)
{
nCompRem = 1;
}
else
{
nCompRem = 0;
}
nSum = nSum + (nPos*nRemider);
nCompSum = nCompSum + (nPos*nCompRem);
_itoa(nCompRem,ChArray,10);
strComp = strComp + string(ChArray);
nTempNum = nTempNum / 2;
nPos = nPos * 10;
} while (nTempNum>0);
cout << "\n The Binary equivalent of " << nInputNum << " is " << nSum;
int nIntComp = 0;
nPos = 0;
nRemider = 0;
while (nCompSum > 0)
{
nRemider = nCompSum % 10;
nIntComp = nIntComp + pow(2,nPos)*nRemider;
nCompSum = nCompSum / 10;
nPos++;
}
reverse(strComp.begin(),strComp.end());
cout << "\n The complement Binary equivalent" << " is " << strComp;
return nIntComp;
}
void main()
{
int nNumber;
cout << "\n Enter a number to Convert to Binary";
cin >> nNumber;
cout << "\n The Integer complement of " << nNumber << " is " << GetIntegerComplement(nNumber);
_getch();
}
C# Source:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DecimalOnceComplement
{
class Program
{
static int GetIntegerComplement(int nInputNum)
{
int nRemider = 0, nCompRem = 0, nSum = 0, nCompSum=0, nTempNum;
int nPos=1;
string strComp="";
nTempNum = nInputNum;
do
{
nRemider = nTempNum % 2;
if (nRemider == 0)
{
nCompRem = 1;
}
else
{
nCompRem = 0;
}
nSum = nSum + (nPos*nRemider);
nCompSum = nCompSum + (nPos*nCompRem);
strComp = strComp + nCompRem.ToString();
nTempNum = nTempNum / 2;
nPos = nPos * 10;
} while (nTempNum>0);
Console.WriteLine(" The Binary equivalent of {0} is {1}",nInputNum,nSum);
int nIntComp = 0;
nPos = 0;
nRemider = 0;
while (nCompSum > 0)
{
nRemider = nCompSum % 10;
nIntComp = nIntComp + (int)(Math.Pow(2,nPos))*nRemider;
nCompSum = nCompSum / 10;
nPos++;
}
strComp = ReverseString(strComp);
Console.WriteLine( " The complement Binary equivalent is {0}",strComp);
return nIntComp;
}
public static string ReverseString(string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
static void Main(string[] args)
{
int nNumber;
string strInput;
Console.WriteLine(" Enter a number to Convert to Binary:");
strInput = Console.ReadLine();
nNumber = Convert.ToInt32(strInput);
Console.WriteLine(" The Integer complement of {0} is {1}" ,nNumber,GetIntegerComplement(nNumber));
Console.ReadLine();
}
}
}
Out Put :
No comments:
Post a Comment