BITMAGIC - Editorial

PROBLEM LINK:

Practice
Contest

Author: Rajendra Prajapat
Tester: Amitabh Paliwal
Editorialist: Rajendra Prajapat,Amitabh Paliwal

DIFFICULTY:

EASY

PREREQUISITES:

bit-manipulation, bitwise operation

PROBLEM:

Given a number ’n’ and a position ‘k’. Set the kth bit of n to 1 if it is not set(i.e. 0), otherwise, leave it as it is.

QUICK EXPLANATION:

Left shift 1 by k and perform bitwise or (|) with the number n, it will set the kth bit.

EXPLANATION:

When we left shift 1 by k, we get the binary number with kth bit set, then if the kth bit is set the bitwise or(|) will leave it unchanged else if it is zero the result of the bitwise or(|) will be 1.

SOLUTIONS:

Setter's Solution
#include<iostream>
using namespace std;
typedef unsigned long long ull;
int main()
{
          ios::sync_with_stdio(0);
         cin.tie(0);        
         int t;
         cin>>t;
         while(t--)
         {
                int n,k;
                cin>>n>>k;
                unsigned int ans = n|(1<<k);
                cout<<ans<<endl;
          }
}