[微软面试题]二进制加法

Implement a function that performs binary addition. Input to the function is two const strings. The function returns a string that holds the result of addition.
char* binaryadd(const char* a, const char* b) { }
Eg. "1001"+"101"="1110"

char* binaryadd(const char* a, const char* b)
{
int nA;
sscanf(a,
"%d", &nA);
int nB;
sscanf(b,
"%d", &nB);

char tmp[32] = {0};
itoa(nA
+nB, tmp, 10);

int nResult = 0;
int nLenth = strlen(tmp);
for(int i=nLenth-1,j=0; i>=0; i--)
{
if(tmp[i] == '1')
nResult
+= 1<<j;
else if(tmp[i] == '2')
nResult
+= 1<<(j+1);
j
++;
}

char* sResult = new char[32];
memset(sResult,
0, 32);
itoa(nResult, sResult,
2);

return sResult;
}

 
有好方法的同学不要客气哈!
posted @ 2011-08-25 13:13  清秋  Views(253)  Comments(0)    收藏  举报