给定一个正整数’n’,在其二进制表示中具有’x’个置位位数。问题在于找到前一个较小的整数(小于n的最大整数),在其二进制表示形式中具有(x-1)个设置位。
注意: 1 <= n
例子 :
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
步骤如下:
- 在n的二进制表示中找到最右置位的位置(考虑位置1的最后一位,位置2的最后一位,依此类推)。让位置用pos表示。请参阅这篇文章。
- 关闭或取消设置位置pos的位。请参阅这篇文章。
C++
// C++ implementation to find the previous
// smaller integer with one less number of
// set bits
#include
using namespace std;
// function to find the position of
// rightmost set bit.
int getFirstSetBitPos(int n)
{
return log2(n & -n) + 1;
}
// function to find the previous smaller
// integer
int previousSmallerInteger(int n)
{
// position of rightmost set bit of n
int pos = getFirstSetBitPos(n);
// turn off or unset the bit at
// position 'pos'
return (n & ~(1 << (pos - 1)));
}
// Driver program
int main()
{
int n = 25;
cout << previousSmallerInteger(n);
return 0;
}
Java
// Java implementation to find the previous
// smaller integer with one less number of
// set bits
class GFG {
// function to find the position of
// rightmost set bit.
static int getFirstSetBitPos(int n)
{
return (int)(Math.log(n & -n) / Math.log(2)) + 1;
}
// function to find the previous smaller
// integer
static int previousSmallerInteger(int n)
{
// position of rightmost set bit of n
int pos = getFirstSetBitPos(n);
// turn off or unset the bit at
// position 'pos'
return (n & ~(1 << (pos - 1)));
}
// Driver code
public static void main(String[] args)
{
int n = 25;
System.out.print("Previous smaller Integer ="
+ previousSmallerInteger(n));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python3 implementation to find
# the previous smaller integer with
# one less number of set bits
import math
# Function to find the position
# of rightmost set bit.
def getFirstSetBitPos(n):
return (int)(math.log(n & -n) /
math.log(2)) + 1
# Function to find the
# previous smaller integer
def previousSmallerInteger(n):
# position of rightmost set bit of n
pos = getFirstSetBitPos(n)
# turn off or unset the bit
# at position 'pos'
return (n & ~(1 << (pos - 1)))
# Driver code
n = 25
print("Previous small Integer = ",
previousSmallerInteger(n))
# This code is contributed by Anant Agarwal.
C#
// C# implementation to find the previous
// smaller integer with one less number of
// set bits
using System;
class GFG {
// function to find the position of
// rightmost set bit.
static int getFirstSetBitPos(int n)
{
return (int)(Math.Log(n & -n) /
Math.Log(2)) + 1;
}
// function to find the previous smaller
// integer
static int previousSmallerInteger(int n)
{
// position of rightmost set bit of n
int pos = getFirstSetBitPos(n);
// turn off or unset the bit at
// position 'pos'
return (n & ~(1 << (pos - 1)));
}
// Driver code
public static void Main()
{
int n = 25;
Console.WriteLine("Previous small Integer ="
+ previousSmallerInteger(n));
}
}
// This code is contributed by anant321.
PHP
Javascript
输出 :
Previous smaller integer = 24