diff options
| -rw-r--r-- | challenge-192/james-smith/README.md | 10 |
1 files changed, 7 insertions, 3 deletions
diff --git a/challenge-192/james-smith/README.md b/challenge-192/james-smith/README.md index e015cf6ddb..76dac905f8 100644 --- a/challenge-192/james-smith/README.md +++ b/challenge-192/james-smith/README.md @@ -47,11 +47,14 @@ This can also be done by converting to a string and then coverting back again. ``` sub string_flip { - oct '0b'.sprintf('%b',$_[0])=~tr/01/10/r; + $_[0] ? oct '0b'.sprintf('%b',$_[0])=~tr/01/10/r : 0; +} ``` We use `tr` with the `r` option to return the result of the translation... +Note we have to check whether the input is `0` as in this case the output is also `0` as there is no leading 1. + ### Performance... Well this is where Perl is uber fast when it comes to strings - the string solution is faster than the bit manipulation. This is probably due to the overhead of each separate operation in the numeric version. For a test example of "12345678" (`1011 1100 0110 0001 0100 1110`) the string method is 8x faster than the binary method. @@ -79,10 +82,11 @@ A further re-write of the C gives: ```C int c2(int n) { int o = n; - int m = 1; - while(o>>=1) { + int m = 0; + while(o) { m<<=1; m++; + o>>=1 } return n^m; } |
