22
1
Background
The Hamming weight of an integer is the number of ones in its binary representation. For this challenge, integers are represented with 32 bits, and they are unsigned.
Challenge
Given an integer between 0 and 2^32-1 (non-inclusive), output a different integer within the same range, and also with the same Hamming weight.
Examples
Input (Decimal) | Input (Binary) | Hamming weight | Possible output (Decimal)
46 | 0b0010 1110 | 4 | 15
12 | 0b0000 1100 | 2 | 3
1 | 0b0000 0001 | 1 | 2
3 | 0b0000 0011 | 2 | 6
2^31 | 0b1000....0 | 1 | 1
2^31+2 | 0b1000...10 | 2 | 3
2^32-5 | 0b1111..011 | 31 | 2^31-1
2^32-2 | 0b1111....0 | 31 | 2^31-1
0 | 0b0000 0000 | 0 | None (This case need not be handled)
2^32-1 | 0b1111....1 | 32 | None (This case need not be handled)
Scoring
This is code-golf, so the solution in the fewest bytes in each language wins.
2I'd suggest adding an odd number between 2^31+1 and 2^32-3, as some answers are failing at that. – Ørjan Johansen – 2017-06-02T08:06:05.963
Related. – Martin Ender – 2017-06-02T08:49:46.783
Since you just added
2^31+2
, I'll repeat that I said an odd number. The answers in question only failed when both the highest and the lowest bit are1
. – Ørjan Johansen – 2017-06-03T04:16:57.243I'm a fool. Thank you. Will fix that – musicman523 – 2017-06-03T12:10:44.110
1@musicman523 I just happened to be browsing active questions and saw this one. And noticed that you still haven't added the requested test cases. – Draco18s no longer trusts SE – 2019-04-29T13:47:58.747
@Draco18s I haven't really been active on here in a couple years. Would you like to add the requested test cases? – musicman523 – 2019-04-30T13:35:01.637
They'd be nice! I don't plan on writing an answer, I was just a bit amused and thought I'd ping. :) – Draco18s no longer trusts SE – 2019-04-30T13:51:59.783
Ok, I added 2^32-5 as a test case – musicman523 – 2019-04-30T15:54:27.573