给定正整数N ,任务是找到标尺函数系列的第N个项。
The Ruler Function Series is a series, having 1 as the first term, formed by performing the following two operations:
- Append the smallest positive integer not present in the series.
- Then, append all the numbers before the last number.
例子:
Input: N = 5
Output: 1
Explanation: The Ruler Function Series is given by {1, 2, 1, 3, 1, 2, 1, 4, ….. }. Therefore, the 5th term of the series is 1.
Input: N = 8
Output: 4
天真的方法:解决给定问题的最简单方法是生成序列,直到第N个项,然后打印第N个项。
时间复杂度: O(N)
辅助空间: O(N)
高效方法:还可以根据以下观察结果对上述方法进行优化,即观察到标尺函数系列中的第N个元素等于(N ^(N – 1))中的设置位数,如下所示:
- 0和1 = 1的按位XOR设置位的数目
- 1和2的按位XOR设置位的位数= 2
- 2和3的按位XOR设置位的位数
- 3和4的按位XOR设置位的位数= 3
- 4和5的按位XOR设置位的位数= 1
- 5和6的按位XOR设置位的位数= 2
- 6和7的按位XOR设置位的位数= 1
- 7和8的按位XOR设置位的位数= 4
- 等等…
因此,根据上述观察,标尺函数系列的第N个项由N与(N – 1)的按位XOR给出。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to count the number
// of set bits in the number N
int setBits(long n)
{
// Store the number of setbits
int count = 0;
while (n > 0) {
// Upate the value of n
n = n & (n - 1);
// Update the count
count++;
}
// Return the total count
return count;
}
// Function to find the Nth term of
// the Ruler Function Series
void findNthTerm(int N)
{
// Store the result
int x = setBits(N ^ (N - 1));
// Print the result
cout << x;
}
// Driver Code
int main()
{
int N = 8;
findNthTerm(N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG{
// Function to count the number
// of set bits in the number N
static int setBits(long n)
{
// Store the number of setbits
int count = 0;
while (n > 0)
{
// Upate the value of n
n = n & (n - 1);
// Update the count
count++;
}
// Return the total count
return count;
}
// Function to find the Nth term of
// the Ruler Function Series
static void findNthTerm(int N)
{
// Store the result
int x = setBits(N ^ (N - 1));
// Print the result
System.out.println(x);
}
// Driver Code
public static void main(String[] args)
{
int N = 8;
findNthTerm(N);
}
}
// This code is contributed by Kingash
输出:
4
时间复杂度: O(log N)
辅助空间: O(1)