Solution of the problem posted in my previous blog
For scenario #1 & #2 there is not much to answer as it is very straight forward. So, I will directly provide you with the answer for the most tricky scenario #3.
The solution posted on the blog of Aaron Ballman -
"It turns out that the way you accomplish it is with an array of 256 function pointers. Every time you get a character, it's ASCII value is an index into the array of function pointers where the entries for '0' through '9' are calculating the value (with the help of a global position value). The entry for the null byte terminates the process and returns the proper value. All of the other entries point to an error function." - Ballman
The solution which I devised, uses a recursive function to achieve the looping functionality and '&&' (Logical And) operator to achieve the flow control functionality. Very simple and straight forward logic to solve a simple problem. Here goes the function StringVal...
int StringVal (const char *buf)
{
int value = 0;
static int index = 1;
const char *tbuf = buf;
(*tbuf != '\0') && (value = StringVal(++buf), value += (*tbuf - 48) * index, index*= 10);
(*tbuf == '\0') && (value = 0);
return value;
}
For interested audience, following links provide a good discussion of the problem and many solutions to it.
1. Original discussion of the problem
2. Answer to the problem
2 comments:
You rocks! Yet another great solution inspire me a lot. I haven't think about && operator for one second. I don't know it can be used so facility. I've looked up "The C Programming Language" and knew why.
Thanks, Vikash.
Hmm... But I still suggest a convert table for character to numeric transform, suppose you're working with a unknown character set or the character set is not indicated by the background, that solution is still portable.
Yes I agree .. the conversion table will make this solution very flexible.. I couldn't think of that .. thanks. :)
Post a Comment