D41d8cd98f00b204e9800998ecf8427e

Here's a puzzle I came up with in case you want to waste some time. What does f() do, and how?

#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 !

D41d8cd98f00b204e9800998ecf8427e

Max

March 13, 2009, March 13, 2009 08:34, permalink

No rating. Login to rate!

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.

D41d8cd98f00b204e9800998ecf8427e

steve.hanov.myopenid.com

March 13, 2009, March 13, 2009 17:17, permalink

No rating. Login to rate!

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));
}
4330db06b64ca72e2e1f62705aed468f

Michael Osuna Jr

March 14, 2009, March 14, 2009 06:12, permalink

No rating. Login to rate!

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;
}
A8d3f35baafdaea851914b17dae9e1fc

Adam

March 17, 2009, March 17, 2009 03:12, permalink

No rating. Login to rate!
int f(const char *s)
{
    int i;
    
    for (i = 0; *s; s++) {
        i = i * 10 + *s - '0';
    }
    
    return i;
}
Edd22df6468533fc8f1823c92b464c49

Flash

March 28, 2009, March 28, 2009 12:19, permalink

No rating. Login to rate!

Good site, admin.

Good site, admin.
D41d8cd98f00b204e9800998ecf8427e

jkhjk

November 25, 2009, November 25, 2009 15:43, permalink

No rating. Login to rate!
uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuiiikjhkjhk


kjlkjlhjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjhg

Your refactoring





Format Copy from initial code

or Cancel