Quantcast
Channel: Break an integer into even- and odd-indexed bits - Code Golf Stack Exchange
Viewing all articles
Browse latest Browse all 15

Answer by Kevin Cruijssen for Break an integer into even- and odd-indexed bits

$
0
0

Java, 79 bytes

int[]f(int n){return new int[]{n*~n<0?f(n>>2)[0]*2|n%2:n,n*~n<0?f(n>>1)[0]:n};}

It's been a while since I've used a recursive approach in Java. Perhaps an iterative lambda with String return could be shorter, but I'm not sure.

Try it online.

Explanation:

int[]f(int n){         // Recursive method with integer parameter & integer-array return:  return new int[]{    //  Return a new integer-array, with two items:    n*~n<0?            //   If `n*(-n-1)` is negative:      f(n>>2)          //    Do a recursive call with `n` bitwise right-shifted by 2             [0]       //    Take its singular result                *2     //    Multiply it by 2                  |    //    Bitwise-OR it by:                   n%2 //     `n` modulo-2    :                  //   Else (`n*(-n-1)` is 0 instead):     n,                //    Simply use `n` as is    n*~n<0?            //   Repeat the same if-statement:      f(n>>1)          //    Do a recursive call to `n` bitwise right-shifted by 1 instead             [0]       //    And take its singular result    :n};}              //   With a similar else-block

Viewing all articles
Browse latest Browse all 15

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>