Browser tab content: You are inside question view of Counting Bits 17m left Skip to main…
- User
Browser tab content: You are inside question view of Counting Bits
17m left Skip to main content ALL 1 2 3
- Counting Bits
Given an integer, n, determine the following:
How many 1-bits are in its binary representation? The number n's binary representation has k significant bits indexed from 1 to k. What are the respective positions of each 1-bit, in ascending order?
For example, the diagram below depicts this information for the value n = 37:
In the binary representation of 37, there are three 1-bits located at the respective 1st, 4th, and 6th positions.
Note: The leftmost 1 bit is always position 1. Preceding zeros are not considered in determining the position.
Function Description
Complete the function getOneBits in the editor below. The function must return a results array with the number of 1's stored at results[0] followed by the positions of all 1's in its binary representation in ascending order.
getOneBits has the following parameter(s):
n: an integer
Constraints
1 < n < 109
Input Format for Custom Testing Sample Case 0
Sample Input
161
Sample Output
3 1 3 8
Explanation
The integer n = (161)10 converts to (10100001)2:
In the binary representation of 161, there are 3 1-bits located at the 1st, 3rd, and 8th positions.
Because there are three 1-bits, the return array is 3 + 1 = 4 units in length. Store the 1's count, 3, at index 0. Then store the locations of the 1-bits in order, low to high. Return the array [3, 1, 3, 8] as the answer.
Language Java 17 Environment Autocomplete Ready Switched to light theme More 1 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 import java.io.; class Result { / * Complete the 'getOneBits' function below. * * The function is expected to return an INTEGER_ARRAY. * The function accepts INTEGER n as parameter. */ public static List getOneBits(int n) { // Write your code here } } public class Solution { ? of 4 Line: 14 Col: 1 Test Results Custom Input Compiled successfully.1/7 test cases passed Use print or log statements to debug why your hidden test cases are failing. Hidden test cases are used to evaluate if your code can handle different scenarios, including corner cases. Test case 0 Test case 1 Test case 3 Test case 4 Test case 5 Test case 6 Test case 2 Input (stdin) Run as Custom Input | Download 161 Your Output (stdout) 3 1 6 8 Expected Output Download 3 1 3 8 Run Code Run Tests Submit .collect(joining("\n")), ? of 4 found for 'result', at 41:15
- Assistant