给定一个整数N ,任务是找到正好设置了两位的第N个自然数。
例子:
Input: N = 4
Output: 9
Explanation:
Numbers with exactly two bits set: 3, 5, 6, 9, 10, 12, …
4th number in this is 9
Input: N = 15
Output: 48
天真的方法:
- 循环遍历所有自然数,并通过对数字中的设置位数进行计数,检查每个数字是否设置了两位。
- 打印具有两个设置位的第N个数字。
高效方法:
- 通过找到N所属的分区来找到最左置位(分区’i’中具有’i’数字)。
- 要找到其他设置位,我们必须首先找到N与上一个分区的最后一个数字的距离。根据它们的差异,我们设置相应的位。
- 注意:要在数字K中设置第i位(i = 0、1、2…):
k = k | (1<<(i))
- 下面是上述方法的实现:
C++
// C++ Code to find the Nth number
// with exactly two bits set
#include
using namespace std;
// Function to find the Nth number
// with exactly two bits set
void findNthNum(long long int N)
{
long long int bit_L = 1, last_num = 0;
// Keep incrementing until
// we reach the partition of 'N'
// stored in bit_L
while (bit_L * (bit_L + 1) / 2 < N) {
last_num = last_num + bit_L;
bit_L++;
}
// set the rightmost bit
// based on bit_R
int bit_R = N - last_num - 1;
cout << (1 << bit_L) + (1 << bit_R)
<< endl;
}
// Driver code
int main()
{
long long int N = 13;
findNthNum(N);
return 0;
}
Java
// Java Code to find the Nth number
// with exactly two bits set
class GFG{
// Function to find the Nth number
// with exactly two bits set
static void findNthNum(int N)
{
int bit_L = 1, last_num = 0;
// Keep incrementing until
// we reach the partition of 'N'
// stored in bit_L
while (bit_L * (bit_L + 1) / 2 < N) {
last_num = last_num + bit_L;
bit_L++;
}
// set the rightmost bit
// based on bit_R
int bit_R = N - last_num - 1;
System.out.print((1 << bit_L) + (1 << bit_R)
+"\n");
}
// Driver code
public static void main(String[] args)
{
int N = 13;
findNthNum(N);
}
}
// This code is contributed by Princi Singh
Python3
# Python Code to find the Nth number
# with exactly two bits set
# Function to find the Nth number
# with exactly two bits set
def findNthNum(N):
bit_L = 1;
last_num = 0;
# Keep incrementing until
# we reach the partition of 'N'
# stored in bit_L
while (bit_L * (bit_L + 1) / 2 < N):
last_num = last_num + bit_L;
bit_L+=1;
# set the rightmost bit
# based on bit_R
bit_R = N - last_num - 1;
print((1 << bit_L) + (1 << bit_R));
# Driver code
if __name__ == '__main__':
N = 13;
findNthNum(N);
# This code contributed by PrinciRaj1992
C#
// C# Code to find the Nth number
// with exactly two bits set
using System;
class GFG{
// Function to find the Nth number
// with exactly two bits set
static void findNthNum(int N)
{
int bit_L = 1, last_num = 0;
// Keep incrementing until
// we reach the partition of 'N'
// stored in bit_L
while (bit_L * (bit_L + 1) / 2 < N) {
last_num = last_num + bit_L;
bit_L++;
}
// set the rightmost bit
// based on bit_R
int bit_R = N - last_num - 1;
Console.Write((1 << bit_L) + (1 << bit_R)
+"\n");
}
// Driver code
public static void Main(String[] args)
{
int N = 13;
findNthNum(N);
}
}
// This code is contributed by Princi Singh
Javascript
输出:
36
- 时间复杂度: O(数字分区)
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。