4
\$\begingroup\$

Given a positive integer as input, output that integer, but with its bits rotated two times to the right. Also, think of the number as a donut of bits, eg. 21 -> (10101). If all of the bits suddenly decided to move to the right, they would wrap around. eg. rRot(21) -> (11010) = 26. Do what i explained 2 times (at the same time).

Test cases:

24 -> 6
21 -> 13
32 -> 8
0 -> 0
1 -> 1
3 -> 3

Remember that this is , so the shortest answer in bytes wins!

Also, here's a snippet for the leaderboard:

var QUESTION_ID=244139;
var OVERRIDE_USER=8478;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> 

\$\endgroup\$
13
  • 3
    \$\begingroup\$ Can you define "bits rotated two times to the right?" \$\endgroup\$ Commented Mar 14, 2022 at 21:44
  • 9
    \$\begingroup\$ Can you put that definition in the question? \$\endgroup\$ Commented Mar 14, 2022 at 22:07
  • 5
    \$\begingroup\$ What is expected output for 26? Should rotate one time be 13, and rotate 13 one more time be 14? Almost all current answers output 22 instead. \$\endgroup\$
    – tsh
    Commented Mar 15, 2022 at 6:44
  • 4
    \$\begingroup\$ Your description change does not quite address tsh's comment. Do leading zeros get kept after the first rotation or not - using tsh's example would the conversion and two rotations go like 26 -> 11010 -> 01101 -> 10110 -> 22 or like 26 -> 11010 -> 1101 -> 1110 -> 14? \$\endgroup\$ Commented Mar 15, 2022 at 12:15
  • 2
    \$\begingroup\$ Cool, thanks - please do update the question to make it clear*. Once that and what to do with negative integers or that we do not need to handle them is clarified then I'll happily vote to reopen. * Also note that many answers are invalidated, so you may want to let people who have posted invalid answers know. \$\endgroup\$ Commented Mar 15, 2022 at 14:18

19 Answers 19

6
\$\begingroup\$

Vyxal, 4 bytes

bǔǔB

Try it Online!

All these languages without rotate right built-ins smh.

Explained

bǔǔB
b    # convert input to binary
 ǔ   # rotate that right once
  ǔ  # and rotate that right all over again. 
   B # convert back to base 10 
\$\endgroup\$
4
\$\begingroup\$

MathGolf, 2 bytes

╪╪

Try it online.

Explanation:

╪   # Rotate the bits of the (implicit) input-integer once towards the right
 ╪  # And do it again
    # (after which the entire stack is output implicitly as result)
\$\endgroup\$
2
  • \$\begingroup\$ What the hell...? \$\endgroup\$
    – Joao-3
    Commented Mar 15, 2022 at 11:26
  • \$\begingroup\$ @FelipeSoares I dunno. 🤷 Ask maxb I guess. He created the language. ;) If I had to guess, he added the / as a general rotate for strings/lists, and figured that for integer-arguments rotating the bits would be a potentially useful alternative. \$\endgroup\$ Commented Mar 15, 2022 at 12:13
4
\$\begingroup\$

05AB1E, 6 4 bytes

-2 bytes thanks to Kevin Cruijssen

bÁÁC

Try it online!

Explanation:

         # implicit input
b        # convert to binary
 ÁÁ      # rotate right twice
    C    # convert from binary to decimal
         # implicitly output
\$\endgroup\$
2
  • 3
    \$\begingroup\$ Welcome to CGCC. You can save 2 bytes by using the binary-string buitlins instead of the base-list builtins. :) can be b and can be C. \$\endgroup\$ Commented Mar 15, 2022 at 7:55
  • 1
    \$\begingroup\$ @Kevin Thanks, I thought there might be something like that but could not find it first time in the docs. Now I know for future uses! \$\endgroup\$
    – nextwayup
    Commented Mar 15, 2022 at 11:22
4
\$\begingroup\$

R, 59 58 46 bytes

Edit: -1 byte thanks to Giuseppe, and then a change-of-approach benefitting heavily from Giuseppe's golfing again

function(x,z=x%/%4)z+2^(log2(z*2+!z)%/%1)*x%%4

Try it online!

Integer-divide x by 4, and then add x modulo 4 multiplied by 2^ceiling(log2(x/4)).


Or, if the rotation is done in two separate steps, with removal of leading zeros after each step:

R, 61 56 bytes

Edit: -5 bytes thanks to Giuseppe

function(x,z=x%/%4)z+2^(log2(z*2+!z)%/%1)*(x%%4-!x%%4-2)

Try it online!

Integer-divide x by 4, and then add the number of 1-bits of x modulo 4 multiplied by 2^ceiling(log2(x/4)). Works because each rotation only adds a 1 to the front if the least-significant-bit is non-zero.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ log2 is a byte shorter than log(,2) \$\endgroup\$
    – Giuseppe
    Commented Mar 15, 2022 at 16:17
  • \$\begingroup\$ @Giuseppe - Thanks! \$\endgroup\$ Commented Mar 15, 2022 at 17:09
  • 1
    \$\begingroup\$ Your second one can be 59 bytes if you replace (y==2) with !y-2 and 58 if you use (x%%4-!x%%4-2) instead. I think this would work for 56 but it might break down somewhere. \$\endgroup\$
    – Giuseppe
    Commented Mar 15, 2022 at 18:47
  • 1
    \$\begingroup\$ @Giuseppe - Thanks again. I think your 56-byter seems Ok (the zero case was the biggest problem I was worrying about...)... and I realized that the integer-divide-and-add-modulo-times-power-of-2 approach is shorter than the first one, so you helped that a lot, too! \$\endgroup\$ Commented Mar 15, 2022 at 22:06
3
\$\begingroup\$

APL (dzaima/APL), 6 bytes

Anonymous tacit prefix function.

¯2∘⌽⍢⊤

Try it online! (TIO is outdated; the 0 case works in the latest version)

¯2∘⌽ rotate two steps right

 under

 binarification

Compare to "surgery under anaesthesia" — the anaesthesia is undone once the surgery is over.

\$\endgroup\$
3
\$\begingroup\$

APL (Dyalog Extended), 5 bytes

Anonymous tacit prefix function

⊥¯2⌽⊤

Try it online!

 from-base-2 of

¯2⌽ negative two left rotations of

 to-base-2

\$\endgroup\$
3
\$\begingroup\$

Brachylog, 6 bytes

ḃ↻₂⊇~ḃ

Try it online!

ḃ         Convert to binary,
 ↻₂       and rotate right 2.
   ⊇      Try subsequences largest first until
    ~ḃ    it can be converted from binary without leading zeroes.
\$\endgroup\$
3
\$\begingroup\$

Desmos, 82 bytes

k=floor(log_2(n+0^n))
l=[0...k]
f(n)=total(mod(floor(n/2^l),2)[mod(l+2,k+1)+1]2^l)

Try It On Desmos!

Try It On Desmos! - Prettified

Thanks @Bubbler for supplying a helpful formula in the chat (I did l+2 instead of l-2, though, because I realized it was golfier to do that).

\$\endgroup\$
2
\$\begingroup\$

Jelly, 5 bytes

Bṙ-2Ḅ

Try It Online!

Bṙ-2Ḅ  Main Link
B      convert to base 2
 ṙ-2   rotate left -2 times
    Ḅ  convert from base 2
\$\endgroup\$
2
\$\begingroup\$

Charcoal, 15 bytes

≔↨N²θI↨²Eθ§θ⁻κ²

Try it online! Link is to verbose version of code. Explanation:

≔↨N²θ

Convert the input integer to binary.

I↨²Eθ§θ⁻κ²

Rotate the array by two bits and convert it back from binary.

\$\endgroup\$
2
\$\begingroup\$

Retina 0.8.2, 50 bytes

.+
$*
+`(1+)\1
$1_
r`(.+)(_1?_1?)
$2_$1
+`1_
_11
1

Try it online! Link includes test cases. Explanation:

.+
$*

Convert to unary.

+`(1+)\1
$1_

Convert to a modified binary where _ represents 0 and _1 represents 1. (Another way of thinking of it is that each 1's value depends only on the number of following _s.)

r`(.+)(_1?_1?)
$2_$1

Rotate the last two bits of the number to the start.

+`1_
_11

Convert back to unary.

1

Convert to decimal.

\$\endgroup\$
2
\$\begingroup\$

Wolfram Language (Mathematica), 33 bytes

2^BitLength[a=⌊#/4⌋](#-4a)+a&

Try it online!

\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 29 bytes

n=>n%4<<32-Math.clz32(n/=4)|n

Try it online!

Commented

n =>          // n = input
  n % 4       // isolate the two least significant bits
  <<          // left-shift them by
  32 -        // the bit length of n once it has been divided by 4
  Math.clz32( // this is computed by using the number of leading
    n /= 4    // zeros in the 32-bit representation
  )           //
  | n         // bitwise OR with n (which is now input / 4)
\$\endgroup\$
3
  • \$\begingroup\$ Don't just assume that the integer is 32-bit (aka ranging from -2147483648 to 2147483647). \$\endgroup\$
    – Joao-3
    Commented Mar 15, 2022 at 11:42
  • 1
    \$\begingroup\$ @FelipeSoares That's against this site normal policy for this type of challenge. Of course as poster you can choose whatever rules you like. But why have a bit oriented challenge that can't assume 32/64 bit integers? Rules out languages like C. And makes it less fun. \$\endgroup\$
    – Noodle9
    Commented Mar 15, 2022 at 12:26
  • 2
    \$\begingroup\$ @FelipeSoares In addition to what Noodle9 said, be careful not to turn this into a chameleon challenge where the real task is to support arbitrary size integers. \$\endgroup\$
    – Arnauld
    Commented Mar 15, 2022 at 14:18
2
\$\begingroup\$

Ruby, 31 29 bytes

->n{n%4<<(n/=4).bit_length|n}

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Python 3, 34 bytes (@m90)

lambda n:n%4<<len(bin(n|2))-4|n>>2

Try it online!

Old Python 3, 37 bytes

lambda n:(n%4<<len(bin(n>>1))-1)+n>>2

Try it online!

Mostly straight forward. The only bit that needs a bit of care is very small numbers because their bits may wrap around more than once. Here this is solved by making sure that the wrap around shift (the one that is applied to the two smallest bits) is always at least 2.

\$\endgroup\$
1
  • \$\begingroup\$ Improvement: lambda n:n%4<<len(bin(n|2))-4|n>>2 \$\endgroup\$
    – m90
    Commented Mar 15, 2022 at 8:24
2
\$\begingroup\$

Husk, 5 bytes

ḋṙ_2ḋ

Try it online!

    ḋ  # binary digits from number
 ṙ_2   # rotate left -2 positions
ḋ      # number from binary digits

Or 7 bytes if the rotation is done in two separate steps, with removal of leading zeros after each step:

‼(ḋṙ_1ḋ

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Factor, 23 bytes

[ >bin -2 rotate bin> ]

enter image description here

           ! 24
>bin       ! "11000"
-2 rotate  ! "00110"
bin>       ! 6
\$\endgroup\$
1
\$\begingroup\$

Pyth, 9 bytes

i.>.BQ2 2

Try it online!

\$\endgroup\$
1
\$\begingroup\$

C (gcc), 57 bytes

i;f(n){for(i=2;i--;n/=2)n+=n%2<<32-__builtin_clz(n);i=n;}

Try it online!

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.