Interview Question
Software Engineer in TestsC#
int HexToDec(string hex)
{
int i = Int32.Parse(hex, NumberStyles.HexNumber);
return i.ToString();
}
int HexDecimalMap(char ch)
{
if (ch >= '0' && ch <='9')
{
return (ch-'0');
}
if (ch >= 'a' && ch <= 'f')
{
return (10+ (ch-'a');
}
else if (ch >= 'A' && ch <= 'F')
{
return (10+ (ch-'A');
}
else
{
return -1;
}
}
int HexToDecimal(char *str)
{
int num = 0;
while (*str)
{
int numMap = HexDecimalMap(str++);
if (numMap < 0)
{
return -1; //error
}
num = num * 16 + numMap;
}
return num;
}
@r.ramkumar: This has a small bug(coversion bug):The while loop should be like
while(*str)
{
char ch=*str;
str++;
int numMap=HexDecimalMap(ch);
......rest code is fine
Well I would say there is a bug but not the one you pointed out. The bug is num is not incremented. num should be incremented at the end of while loop.
Ramkumar : I think there is a bug. You are multiplying the MSB(left->right in the input) 0*16+numMap,
This needs to be done actually for the LSB.
<pre lang="c++" line="1" title="CodeMonkey17673" class="run-this">first convert heximal value into string (or char[])
- Anonymous December 10, 2010int HexToDec(string hex)
{
int dec(0);
size_t len = hex.size();
int _16mul = 1;
for(size_t i = len; i > 0; --i) {
char number = static_cast<char>(tolower(hex[i - 1]));
if(number >= '0' && number <= '9')
dec += (number - '0') * _16mul;
else if(number >= 'a' && number <= 'f')
dec += (number - 'a' + 10) * _16mul;
else cout << "wrong symbol: " << number << endl;
_16mul *= 16;
}
return dec;
}</pre><pre title="CodeMonkey17673" input="yes">
</pre>