Practice › Bit Manipulation
Check if Kth Bit is Set
Easy · Bit Manipulation · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Print YES if bit k of n is 1, otherwise NO. Bits are numbered from 0 (the least significant bit).
Input
A single line: n k.
Output
YES or NO.
Constraints
- 0 ≤ n ≤ 10^18
- 0 ≤ k ≤ 62
Check (n >> k) & 1, or n & (1 << k) — use a 64-bit shift.
Example 1
Input
5 0
Output
YES
Example 2
Input
5 1
Output
NO
Hints
- Shift n right by k: the bit you want moves to position 0.
- Then AND with 1. Use 64-bit numbers — n can be up to 10^18.
Approach
(n >> k) & 1 is 1 exactly when bit k is set. The alternative n & (1 << k) needs a 64-bit one (1LL << k in C++, 1L << k in Java) or it overflows for k ≥ 31.
Complexity: O(1) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
unsigned long long n;
int k;
cin >> n >> k;
cout << (((n >> k) & 1ULL) ? "YES" : "NO") << "\n";
return 0;
}Python solution
n, k = map(int, input().split())
print("YES" if (n >> k) & 1 else "NO")Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
int k = sc.nextInt();
System.out.println(((n >> k) & 1L) == 1L ? "YES" : "NO");
}
}Solve Check if Kth Bit is Set online · All practice problems