Find most significant set bit of a number
Last Updated :
06 Apr, 2023
Given a number, find the greatest number less than the given a number which is the power of two or find the most significant bit number .
Examples:
Input: 10
Output: 8
Explanation:
Greatest number which is a Power of 2 less than 10 is 8
Binary representation of 10 is 1010
The most significant bit corresponds to decimal number 8.
Input: 18
Output: 16
A simple solution is to one by one divide n by 2 until it becomes 0 and increment a count while doing this. This count actually represents the position of MSB.
C++
// Simple CPP program to find MSB number
// for given POSITIVE n.
#include <iostream>
using namespace std;
int setBitNumber(int n)
{
if (n == 0)
return 0;
int msb = 0;
n = n / 2;
while (n != 0) {
n = n / 2;
msb++;
}
return (1 << msb);
}
// Driver code
int main()
{
int n = 0;
cout << setBitNumber(n);
n = ~(int)0; // test for possible overflow
cout << "\n" << (unsigned int)setBitNumber(n);
return 0;
}
C
#include <stdio.h>
int setBitNumber(int n)
{
if (n == 0)
return 0;
int msb = 0;
n = n / 2;
while (n != 0) {
n = n / 2;
msb++;
}
return (1 << msb);
}
int main() {
int n = 0;
printf("%d \n",setBitNumber(n));
n = ~(int)0; // test for possible overflow
int ns = (unsigned int)setBitNumber(n);
printf("%d",ns);
return 0;
}
Java
// Simple Java program to find
// MSB number for given n.
import java.io.*;
class GFG {
static int setBitNumber(int n)
{
if (n == 0)
return 0;
int msb = 0;
n = n / 2;
while (n != 0) {
n = n / 2;
msb++;
}
return (1 << msb);
}
// Driver code
public static void main(String[] args)
{
int n = 0;
System.out.println(setBitNumber(n));
}
}
// This code is contributed by ajit
Python3
# Simple Python3 program
# to find MSB number
# for given n.
def setBitNumber(n):
if (n == 0):
return 0;
msb = 0;
n = int(n / 2);
while (n > 0):
n = int(n / 2);
msb += 1;
return (1 << msb);
# Driver code
n = 0;
print(setBitNumber(n));
# This code is contributed
# by mits
C#
// Simple C# program to find
// MSB number for given n.
using System;
class GFG {
static int setBitNumber(int n)
{
if (n == 0)
return 0;
int msb = 0;
n = n / 2;
while (n != 0) {
n = n / 2;
msb++;
}
return (1 << msb);
}
// Driver code
static public void Main()
{
int n = 0;
Console.WriteLine(setBitNumber(n));
}
}
// This code is contributed
// by akt_mit
PHP
<?php
// Simple PhP program
// to find MSB number
// for given n.
function setBitNumber($n)
{
if ($n == 0)
return 0;
$msb = 0;
$n = $n / 2;
while ($n != 0)
{
$n = $n / 2;
$msb++;
}
return (1 << $msb);
}
// Driver code
$n = 0;
echo setBitNumber($n);
// This code is contributed
// by akt_mit
?>
JavaScript
<script>
// Javascript program
// to find MSB number
// for given n.
function setBitNumber(n)
{
if (n == 0)
return 0;
let msb = 0;
n = n / 2;
while (n != 0)
{
n = $n / 2;
msb++;
}
return (1 << msb);
}
// Driver code
let n = 0;
document.write (setBitNumber(n));
// This code is contributed by Bobby
</script>
Time Complexity: O(logn)
Auxiliary Space: O(1)
An efficient solution for a fixed size integer (say 32 bits) is to one by one set bits, then add 1 so that only the bit after MSB is set. Finally right shift by 1 and return the answer. This solution does not require any condition checking.
C++
// CPP program to find MSB number for ANY given n.
#include <iostream>
#include <limits.h>
using namespace std;
int setBitNumber(int n)
{
// Below steps set bits after
// MSB (including MSB)
// Suppose n is 273 (binary
// is 100010001). It does following
// 100010001 | 010001000 = 110011001
n |= n >> 1;
// This makes sure 4 bits
// (From MSB and including MSB)
// are set. It does following
// 110011001 | 001100110 = 111111111
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
// The naive approach would increment n by 1,
// so only the MSB+1 bit will be set,
// So now n theoretically becomes 1000000000.
// All the would remain is a single bit right shift:
// n = n + 1;
// return (n >> 1);
//
// ... however, this could overflow the type.
// To avoid overflow, we must retain the value
// of the bit that could overflow:
// n & (1 << ((sizeof(n) * CHAR_BIT)-1))
// and OR its value with the naive approach:
// ((n + 1) >> 1)
n = ((n + 1) >> 1) |
(n & (1 << ((sizeof(n) * CHAR_BIT)-1)));
return n;
}
// Driver code
int main()
{
int n = 273;
cout << setBitNumber(n);
n = ~(int)0; // test for possible overflow
cout << "\n" << (unsigned int)setBitNumber(n);
return 0;
}
C
#include <stdio.h>
#include <limits.h>
int setBitNumber(int n)
{
// Below steps set bits after
// MSB (including MSB)
// Suppose n is 273 (binary
// is 100010001). It does following
// 100010001 | 010001000 = 110011001
n |= n >> 1;
// This makes sure 4 bits
// (From MSB and including MSB)
// are set. It does following
// 110011001 | 001100110 = 111111111
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
// The naive approach would increment n by 1,
// so only the MSB+1 bit will be set,
// So now n theoretically becomes 1000000000.
// All the would remain is a single bit right shift:
// n = n + 1;
// return (n >> 1);
//
// ... however, this could overflow the type.
// To avoid overflow, we must retain the value
// of the bit that could overflow:
// n & (1 << ((sizeof(n) * CHAR_BIT)-1))
// and OR its value with the naive approach:
// ((n + 1) >> 1)
n = ((n + 1) >> 1) |
(n & (1 << ((sizeof(n) * CHAR_BIT)-1)));
return n;
}
int main() {
int n = 273;
printf("%d\n",setBitNumber(n));
return 0;
}
Java
// Java program to find MSB
// number for given n.
class GFG {
static int setBitNumber(int n)
{
// Below steps set bits after
// MSB (including MSB)
// Suppose n is 273 (binary
// is 100010001). It does following
// 100010001 | 010001000 = 110011001
n |= n >> 1;
// This makes sure 4 bits
// (From MSB and including MSB)
// are set. It does following
// 110011001 | 001100110 = 111111111
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
// Increment n by 1 so that
// there is only one set bit
// which is just before original
// MSB. n now becomes 1000000000
n = n + 1;
// Return original MSB after shifting.
// n now becomes 100000000
return (n >> 1);
}
// Driver code
public static void main(String arg[])
{
int n = 273;
System.out.print(setBitNumber(n));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python program to find
# MSB number for given n.
def setBitNumber(n):
# Below steps set bits after
# MSB (including MSB)
# Suppose n is 273 (binary
# is 100010001). It does following
# 100010001 | 010001000 = 110011001
n |= n>>1
# This makes sure 4 bits
# (From MSB and including MSB)
# are set. It does following
# 110011001 | 001100110 = 111111111
n |= n>>2
n |= n>>4
n |= n>>8
n |= n>>16
# Increment n by 1 so that
# there is only one set bit
# which is just before original
# MSB. n now becomes 1000000000
n = n + 1
# Return original MSB after shifting.
# n now becomes 100000000
return (n >> 1)
# Driver code
n = 273
print(setBitNumber(n))
# This code is contributed
# by Anant Agarwal.
C#
// C# program to find MSB number for given n.
using System;
class GFG {
static int setBitNumber(int n)
{
// Below steps set bits after
// MSB (including MSB)
// Suppose n is 273 (binary
// is 100010001). It does following
// 100010001 | 010001000 = 110011001
n |= n >> 1;
// This makes sure 4 bits
// (From MSB and including MSB)
// are set. It does following
// 110011001 | 001100110 = 111111111
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
// Increment n by 1 so that
// there is only one set bit
// which is just before original
// MSB. n now becomes 1000000000
n = n + 1;
// Return original MSB after shifting.
// n now becomes 100000000
return (n >> 1);
}
// Driver code
public static void Main()
{
int n = 273;
Console.WriteLine(setBitNumber(n));
}
}
// This code is contributed by Sam007.
PHP
<?php
// PHP program to find
// MSB number for given n.
function setBitNumber($n)
{
// Below steps set bits
// after MSB (including MSB)
// Suppose n is 273 (binary
// is 100010001). It does
// following 100010001 |
// 010001000 = 110011001
$n |= $n >> 1;
// This makes sure 4 bits
// (From MSB and including
// MSB) are set. It does
// following 110011001 |
// 001100110 = 111111111
$n |= $n >> 2;
$n |= $n >> 4;
$n |= $n >> 8;
$n |= $n >> 16;
// Increment n by 1 so
// that there is only
// one set bit which is
// just before original
// MSB. n now becomes
// 1000000000
$n = $n + 1;
// Return original MSB
// after shifting. n
// now becomes 100000000
return ($n >> 1);
}
// Driver code
$n = 273;
echo setBitNumber($n);
// This code is contributed
// by akt_mit
?>
JavaScript
<script>
// Javascript program to find MSB
// number for given n.
function setBitNumber(n)
{
// Below steps set bits after
// MSB (including MSB)
// Suppose n is 273 (binary
// is 100010001). It does following
// 100010001 | 010001000 = 110011001
n |= n >> 1;
// This makes sure 4 bits
// (From MSB and including MSB)
// are set. It does following
// 110011001 | 001100110 = 111111111
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
// Increment n by 1 so that
// there is only one set bit
// which is just before original
// MSB. n now becomes 1000000000
n = n + 1;
// Return original MSB after shifting.
// n now becomes 100000000
return (n >> 1);
}
// Driver code
let n = 273;
document.write(setBitNumber(n));
// This code is contributed by suresh07
</script>
Time Complexity: O(1)
Auxiliary Space: O(1)
Using __builtin_clz(x) (GCC builtin function)
Say for a fixed integer (32 bits), count the number of leading zeroes by using the built-in function and subtract it from 31 to get the position of MSB from left, then return the MSB using left shift operation on 1.
An efficient solution for a fixed size integer (say 32 bits) is to one by one set bits, then add 1 so that only the bit after MSB is set. Finally right shift by 1 and return the answer. This solution does not require any condition checking.
C++
// CPP program to find MSB
// number for a given POSITIVE n.
#include <bits/stdc++.h>
using namespace std;
int setBitNumber(int n)
{
// calculate the number
// of leading zeroes
int k = __builtin_clz(n);
// To return the value
// of the number with set
// bit at (31 - k)-th position
// assuming 32 bits are used
return 1 << (31 - k);
}
// Driver code
int main()
{
int n = 273;
cout << setBitNumber(n);
n = ~(int)0; // test for possible overflow
cout << "\n" << (unsigned int)setBitNumber(n);
return 0;
}
Java
import java.lang.*;
public class Main {
public static int setBitNumber(int n) {
// calculate the number
// of leading zeroes
int k = Integer.numberOfLeadingZeros(n);
// To return the value
// of the number with set
// bit at (31 - k)-th position
// assuming 32 bits are used
return 1 << (31 - k);
}
// Driver code
public static void main(String[] args) {
int n = 273;
System.out.println(setBitNumber(n));
n = ~(int)0; // test for possible overflow
System.out.println((int)setBitNumber(n));
}
}
// This code is Contributed by 'Shiv1o43g'
C#
using System;
public class MainClass {
public static int SetBitNumber(int n)
{
// calculate the number
// of leading zeroes
int k = 32 - Convert.ToString(n, 2).Length;
// To return the value
// of the number with set
// bit at (31 - k)-th position
// assuming 32 bits are used
return 1 << (31 - k);
}
// Driver code
public static void Main()
{
int n = 273;
Console.WriteLine(SetBitNumber(n));
n = ~(int)0; // test for possible overflow
Console.WriteLine((uint)SetBitNumber(n));
}
}
// This code is contributed by user_dtewbxkn77n
JavaScript
function setBitNumber(n) {
// calculate the number of leading zeroes
let k = 31 - Math.floor(Math.log2(n));
// To return the value of the number with set
// bit at (31 - k)-th position
return 1 << k;
}
// Driver code
let n = 273;
console.log(setBitNumber(n)); // expected output: 256
n = ~(0); // test for possible overflow
console.log(setBitNumber(n)); // expected output: 2147483648
Time Complexity: O(1)
Auxiliary Space: O(1)
Another Approach: Given a number n. First, find the position of the most significant set bit and then compute the value of the number with a set bit at k-th position.
Thanks Rohit Narayan for suggesting this method.
C++
// CPP program to find MSB
// number for given POSITIVE n.
#include <bits/stdc++.h>
using namespace std;
int setBitNumber(int n)
{
//this will be the answer going to return
//This will work for 64-bit if using with long long
//while in-built functions overflow
int ans = 1;
while (n) {
ans *= 2;
n /= 2;
}
ans/=2;
return ans;
}
// Driver code
int main()
{
int n = 273;
cout << setBitNumber(n);
return 0;
}
C
#include <stdio.h>
#include <math.h>
int setBitNumber(int n)
{
if (n == 0)
return 0;
int msb = 0;
n = n / 2;
while (n != 0) {
n = n / 2;
msb++;
}
return (1 << msb);
}
int main() {
int n = 273;
printf("%d",setBitNumber(n));
return 0;
}
Java
// Java program to find MSB
// number for given n.
class GFG {
static int setBitNumber(int n)
{
// To find the position of the
// most significant set bit
int k = (int)(Math.log(n) / Math.log(2));
// To return the value of the number
// with set bit at k-th position
return 1 << k;
}
// Driver code
public static void main(String arg[])
{
int n = 273;
System.out.print(setBitNumber(n));
}
}
Python3
# Python program to find
# MSB number for given n.
import math
def setBitNumber(n):
# To find the position of
# the most significant
# set bit
k = int(math.log(n, 2))
# To return the value
# of the number with set
# bit at k-th position
return 1 << k
# Driver code
n = 273
print(setBitNumber(n))
C#
// C# program to find MSB
// number for given n.
using System;
public class GFG {
static int setBitNumber(int n)
{
// To find the position of the
// most significant set bit
int k = (int)(Math.Log(n) / Math.Log(2));
// To return the value of the number
// with set bit at k-th position
return 1 << k;
}
// Driver code
static public void Main()
{
int n = 273;
Console.WriteLine(setBitNumber(n));
}
}
PHP
<?php
// PHP program to find MSB
// number for given n.
function setBitNumber($n)
{
// To find the position
// of the most significant
// set bit
$k =(int)(log($n, 2));
// To return the value
// of the number with set
// bit at k-th position
return 1 << $k;
}
// Driver code
$n = 273;
echo setBitNumber($n);
// This code is contributed
// by jit_t.
?>
JavaScript
<script>
// Javascript program to find
// MSB number for given n.
function setBitNumber(n)
{
// To find the position of the
// most significant set bit
let k = parseInt(Math.log(n) / Math.log(2), 10);
// To return the value of the number
// with set bit at k-th position
return 1 << k;
}
let n = 273;
document.write(setBitNumber(n));
</script>
Time Complexity: O(logn)
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem