5 kyu

Simple Fun #266: K Bits Digits

92 of 95myjinxin2015

Description:

Task

Return a list of all numbers that have no more than n bits, such that exactly k of them are set to 1.

Input/Output

[input] integer n

The maximum number of bits the number can have.

1 ≤ n ≤ 20.

[input] integer k

The number of bits equal to 1.

0 ≤ k ≤ 20.

[output] an integer array

The numbers with at most n bits k of which are set to 1 sorted in ascending order.

Example

For n = 4 and k = 1, the output should be [1,2,4,8].

110 = 12, which obviously has 1 number of bits, and the only bit is 1.

210 = 102, which has 2 number of bits, with the first one equal to 1.

410 = 1002, which has 3 number of bits, with the first one equal to 1.

810 = 10002, which has 4 number of bits, with the first one equal to 1.

For n = 5 and k = 5, the output should be [31].

3110 = 111112, which exactly has 5 bits qualt to 1.

For n = 3 and k = 20, the output should be [].

No such a number that has not greater 3 bits and exactly has 20 bits qualt to 1.

For n = 20 and k = 0, the output should be [0].

010 = 02, which exactly has 0 bits qualt to 1.

Algorithms
Bits
Binary

Stats:

CreatedMay 11, 2017
PublishedMay 11, 2017
Warriors Trained241
Total Skips24
Total Code Submissions291
Total Times Completed95
JavaScript Completions92
COBOL Completions3
Python Completions3
Total Stars7
% of votes with a positive feedback rating92% of 43
Total "Very Satisfied" Votes37
Total "Somewhat Satisfied" Votes5
Total "Not Satisfied" Votes1
Total Rank Assessments6
Average Assessed Rank
5 kyu
Highest Assessed Rank
5 kyu
Lowest Assessed Rank
7 kyu
Ad
Contributors
  • myjinxin2015 Avatar
  • St3f4n Avatar
  • akar-0 Avatar
  • dfhwze Avatar
Ad