#include <stdio.h>
int f(char*s) {
int a;
a^=a;
while(*s) a=(a<<3)+(a<<1)+*s++-'0';
return a;
}
int main(int argc, char* argv[] ) {
printf("%d\n",f(argv[1]));
return 0;
}
Refactorings
No refactoring yet !
Max
March 13, 2009, March 13, 2009 08:34, permalink
It converts a string representation of an integer (that is a string of characters '0' through '9' of any length) and converts it to an integer.
Nice.
steve.hanov.myopenid.com
March 13, 2009, March 13, 2009 17:17, permalink
Here's a "simpler" way to do it, that avoids the complicated bit manipulation tricks.
#include <stdio.h>
int add(char*s, int n) {
return *s ? add(s+1,*s-'0'+n*10) : n;
}
void main(int argc, char* argv[] ) {
printf("%d\n",add(argv[1],0));
}
Michael Osuna Jr
March 14, 2009, March 14, 2009 06:12, permalink
steve.hanov.myopenid.com creates a recursive call that grows the stack. A "simpler" version that is still iterative might look like below. It is "simpler" in that you don't have to know that a^= a zeros a out and (a << 3) + (a << 1) = (a * 8) + (a * 2) = a * (8 + 2) = a * 10. Also, by initializing a with *s - '0' we don't execute a = 0 + *s++ - '0' the first time through.
#include <stdio.h>
int f(char*s) {
int a = *s - '0';
while(*(++s)) a=a*10+*s-'0';
return a;
}
int main(int argc, char* argv[] ) {
printf("%d\n",f(argv[1]));
return 0;
}
Adam
March 17, 2009, March 17, 2009 03:12, permalink
int f(const char *s)
{
int i;
for (i = 0; *s; s++) {
i = i * 10 + *s - '0';
}
return i;
}
jkhjk
November 25, 2009, November 25, 2009 15:43, permalink
uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuiiikjhkjhk kjlkjlhjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjhg
Here's a puzzle I came up with in case you want to waste some time. What does f() do, and how?