4 ms·
My take, probably present in the original link tho int f(int n) { static int timesCalled = 0; return ++timesCalled % 2 ? n : -n; }
by omegote 13y ago
My take, probably present in the original link tho
int f(int n) {
static int timesCalled = 0;
return ++timesCalled % 2 ? n : -n;
}
- Viper007Bond 13y agoThis was my thought as well. So many people jump to complicated math when the question was about a function. KISS applies, as does out of the box thinking. :) And here's a solution (in PHP, my language of choice) that doesn't use any static variables : function f( $n ) { if ( is_string( $n ) ) { return -1 * (int) $n; } else { return (string) $n; } }