Set all the bits in given range of a number
Last Updated :
27 May, 2022
Given a non-negative number n and two values l and r. The problem is to set the bits in the range l to r in the binary representation of n, i.e, to unset bits from the rightmost lth bit to the rightmost r-th bit.
Constraint: 1 <= l <= r <= number of bits in the binary representation of n.
Examples :
Input : n = 17, l = 2, r = 3
Output : 23
(17)10 = (10001)2
(23)10 = (10111)2
The bits in the range 2 to 3 in the binary
representation of 17 are set.
Input : n = 50, l = 2, r = 5
Output : 62
Approach: Following are the steps:
1. Find a number 'range' that has all set
bits in given range. And all other bits
of this number are 0.
range = (((1 << (l - 1)) - 1) ^
((1 << (r)) - 1));
2. Now, perform "n = n | range". This will
set the bits in the range from l to r
in n.
C++
#include <iostream>
using namespace std;
int setallbitgivenrange( int n, int l, int r)
{
int range = (((1 << (l - 1)) - 1) ^
((1 << (r)) - 1));
return (n | range);
}
int main()
{
int n = 17, l = 2, r = 3;
cout << setallbitgivenrange(n, l, r);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int setallbitgivenrange( int n,
int l, int r)
{
int range = ((( 1 << (l - 1 )) - 1 ) ^
(( 1 << (r)) - 1 ));
return (n | range);
}
public static void main(String[] args)
{
int n = 17 , l = 2 , r = 3 ;
System.out.println(setallbitgivenrange(
n, l, r));
}
}
|
Python3
def setallbitgivenrange(n, l, r):
range = ((( 1 << (l - 1 )) - 1 ) ^
(( 1 << (r)) - 1 ))
return (n | range )
n, l, r = 17 , 2 , 3
print (setallbitgivenrange(n, l, r))
|
C#
using System;
class GFG
{
static int setallbitgivenrange( int n, int l, int r)
{
int range = (((1 << (l - 1)) - 1) ^
((1 << (r)) - 1));
return (n | range);
}
static void Main()
{
int n = 17, l = 2, r = 3;
Console.Write(setallbitgivenrange(n, l, r));
}
}
|
PHP
<?php
function setallbitgivenrange( $n , $l , $r )
{
$range = (((1 << ( $l - 1)) - 1) ^
((1 << ( $r )) - 1));
return ( $n | $range );
}
$n = 17;
$l = 2;
$r = 3;
echo setallbitgivenrange( $n , $l , $r );
?>
|
Javascript
<script>
function setallbitgivenrange(n, l, r)
{
let range = (((1 << (l - 1)) - 1) ^
((1 << (r)) - 1));
return (n | range);
}
let n = 17, l = 2, r = 3;
document.write(setallbitgivenrange(n, l, r));
</script>
|
Output :
23
Time Complexity : O(1)
Auxiliary Space : O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...