-4
Optimize the following function for number of tokens:
int length(int x)
{
switch (x)
{
case 1: return 1;
case 3: return 2;
case 7: return 3;
case 15: return 4;
case 31: return 5;
case 63: return 6;
case 127: return 7;
case 255: return 8;
case 511: return 9;
case 1023: return 10;
case 2047: return 11;
default: return 0;
}
}
No additional cases besides the 11 shown above need to be handled. The default case will never occur (but Java needs one, or else it does not compile). Any programming language is allowed. Whole programs are also allowed.
If you embed another language inside strings, the tokens in the embedded language count as well.
The baseline is 53 tokens, since separators don't seem to count in atomic-code-golf. Have fun!
Should the submissions only be functions or full programs are also allowed ? – Optimizer – 2015-05-01T12:21:33.627
@Optimizer Whole programs are fine. – fredoverflow – 2015-05-01T12:24:39.243
2
possible duplicate of Count the number of ones in unsigned 16 bit integer
– Digital Trauma – 2015-05-01T21:37:12.633Are you saying the code only needs to work for numbers that are one less than a power of 2? – xnor – 2015-05-01T23:21:21.970
@xnor It only needs to work for the numbers 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023 and 2047. – fredoverflow – 2015-05-04T06:55:55.270