Previous smaller integer having one less number of set bits
Last Updated :
15 Nov, 2022
Given a positive integer ‘n’ having ‘x’ number of set bits in its binary representation. The problem is to find the previous smaller integer(greatest integer smaller than n), having (x-1) number of set bits in its binary representation.
Note: 1 <= n
Examples :
Input : 8
Output : 0
(8)10 = (1000)2
is having 1 set bit.
(0)10 = (0)2
is having 0 set bit and is the previous smaller.
Input : 25
Output : 24
The following are the steps:
- Find the position of the rightmost set bit(considering last bit at position 1, second last bit at position 2 and so on) in the binary representation of n. Let the position be represented by pos. Refer this post.
- Turn off or unset the bit at position pos. Refer this post.
C++
#include<bits/stdc++.h>
using namespace std;
int getFirstSetBitPos( int n)
{
return log2(n & -n) + 1;
}
int previousSmallerInteger( int n)
{
int pos = getFirstSetBitPos(n);
return (n & ~(1 << (pos - 1)));
}
int main()
{
int n = 25;
cout << previousSmallerInteger(n);
return 0;
}
|
Java
class GFG {
static int getFirstSetBitPos( int n)
{
return ( int )(Math.log(n & -n) / Math.log( 2 )) + 1 ;
}
static int previousSmallerInteger( int n)
{
int pos = getFirstSetBitPos(n);
return (n & ~( 1 << (pos - 1 )));
}
public static void main(String[] args)
{
int n = 25 ;
System.out.print( "Previous smaller Integer ="
+ previousSmallerInteger(n));
}
}
|
Python3
import math
def getFirstSetBitPos(n):
return ( int )(math.log(n & - n) /
math.log( 2 )) + 1
def previousSmallerInteger(n):
pos = getFirstSetBitPos(n)
return (n & ~( 1 << (pos - 1 )))
n = 25
print ( "Previous small Integer = " ,
previousSmallerInteger(n))
|
C#
using System;
class GFG {
static int getFirstSetBitPos( int n)
{
return ( int )(Math.Log(n & -n) /
Math.Log(2)) + 1;
}
static int previousSmallerInteger( int n)
{
int pos = getFirstSetBitPos(n);
return (n & ~(1 << (pos - 1)));
}
public static void Main()
{
int n = 25;
Console.WriteLine( "Previous small Integer ="
+ previousSmallerInteger(n));
}
}
|
PHP
<?php
function getFirstSetBitPos( $n )
{
return log( $n & - $n ) + 1;
}
function previousSmallerInteger( $n )
{
$pos = getFirstSetBitPos( $n );
return ( $n & ~(1 << ( $pos - 1)));
}
$n = 25;
echo "Previous smaller Integer = " , previousSmallerInteger( $n );
?>
|
Javascript
<script>
function getFirstSetBitPos(n)
{
return parseInt(Math.log(n & -n)/Math.log(2)) + 1;
}
function previousSmallerInteger(n)
{
var pos = getFirstSetBitPos(n);
return (n & ~(1 << (pos - 1)));
}
var n = 25;
document.write( "Previous smaller Integer = " + previousSmallerInteger(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...