Set K Bits

Easy
0/40
Average time to solve is 10m
9 upvotes
Asked in company
Morgan Stanley

Problem statement

Given a number ‘N’. You have to set bits from 0 to Kth position.

Example: If the Given number is 37 (100101) and ‘K’ = 4, then we need to set the 0,1,2,3 bits and thus after the Kth bit set our answer would be 47 (101111).

Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains a single integer ‘T’ representing the number of test cases. 

The first line of each test case will contain two integers ‘N’ and ‘K’ where ‘N’ denotes the number whose 0 to ‘K’th bits have to be set and ‘K’ indicates the limit upto where from 0th bit, the bits have to be set.
Output Format:
For each test case, print the number after 0 to Kth bits are set.

Output for every test case will be printed in a separate line.
Note:
You don’t need to print anything; It has already been taken care of.
Follow Up:
 Can you solve this using O(1) time and space complexity? 
Constraints:
1 <= T <= 10
-10^9 <= N <= 10^9
1 <= K <= 31


Time limit: 1 sec
Sample Input 1:
2
5 2
16 3
Sample Output 1:
7
23
Explanation For Sample Input 1:
In the first test case, we have the number ‘N’ as 5 (101) and K=2. Thus after set 2 bits from the right, the answer will be 7 (111).

In the second test case, we have the number ‘N’ as 16 (10000) and K=3. Thus after set 3 bit from right, the answer will be 23 (10111).
Sample Input 2:
2
10 1
34 4   
Sample Output 2:
11
47
Explanation For Sample Input 2:
In the first test case, we have the number ‘N’ as 10 (1010) and K=1. Thus after set 1 bit from right, the answer will be 11 (1011).

In the second test case, we have the number ‘N’ as 32 (100010) and K=4. Thus after set 3 bit from the right, the answer will be 47 (101111).
Hint

Can you think of it by iterating each bit to be set?

Approaches (2)
Brute Force

The basic idea is to iterate through each bit from 0 till Kth bit and manually set each of the bits irrespective of whether they are set or not. At each index ‘i’ in the iteration manually set each bit and update the number ‘N’ by performing the Bitwise OR of the number ‘N’ with the set bit i.e. (1<<’i’). At last, after iterating, return the number ‘N’.

 

Here is the algorithm: 
 

  1. Run a loop for ‘i’ starting from 0 till less than K:
    • Declare an integer ‘temp’ and assign the value (1<<’i’) to it, where ‘temp’ will store the value where only the ‘i’th bit is set.
    • ‘N’ = ‘N’ | ‘temp’.
  2. Finally after iteration, Return ‘N’.
Time Complexity

O(K), where K is the number of bits which we have to set from the 0th bit.

 

Because we are using a loop that runs K times. Hence the time complexity is O(K).

Space Complexity

O(1), 

 

Because no extra space is used.

Code Solution
(100% EXP penalty)
Set K Bits
Full screen
Console