给定一个整数N和一个数组arr ,该数组包含按排序方式从1到N的整数。任务是通过执行以下操作将数组简化为单个元素:
单个操作后,所有位于奇数位置的元素都将被删除,该操作将执行到数组中只剩下单个元素并最后打印该元素为止。
例子:
Input: N = 3
Output: 2
Initially the array will be arr[] = {1, 2, 3}
After 1st operation, ‘1’ and ‘3’ will be removed and the array becomes arr[] = {2}
So 2 is the only element left at the end.
Input: N = 6
Output: 4
arr[] = {1, 2, 3, 4, 5, 6}
After first iteration, array becomes {2, 4, 6}
After second iteration, array becomes {4}
So 4 is the last element.
方法:针对这种问题:
- 编写多个测试用例以及相应的输出。
- 分析给定输入的输出以及它们之间的关系。
- 一旦找到关系,我们将尽可能尝试以数学表达式的形式来表达它。
- 编写以上表达式的代码/算法。
因此,让我们为给定的输入N及其各自的输出创建一个表
Input(N) | Output |
---|---|
3 | 2 |
4 | 4 |
6 | 4 |
8 | 8 |
12 | 8 |
20 | 16 |
分析关系:输出为2 i 。使用上表,我们可以为输入范围创建输出表
Input(N) | Output |
---|---|
2-3 | 2 |
4-7 | 4 |
8-15 | 8 |
16-31 | 16 |
32-63 | 32 |
2i – 2i + 1 – 1 | 2i |
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the final element
long getFinalElement(long n)
{
long finalNum;
for (finalNum = 2; finalNum * 2 <= n; finalNum *= 2)
;
return finalNum;
}
// Driver code
int main()
{
int N = 12;
cout << getFinalElement(N) ;
return 0;
}
// This code is contributed by Ryuga
Java
// Java implementation of the approach
class OddPosition {
// Function to return the final element
public static long getFinalElement(long n)
{
long finalNum;
for (finalNum = 2; finalNum * 2 <= n; finalNum *= 2)
;
return finalNum;
}
// Driver code
public static void main(String[] args)
{
int N = 12;
System.out.println(getFinalElement(N));
}
}
Python3
# Python 3 implementation of the approach
# Function to return the final element
def getFinalElement(n):
finalNum = 2
while finalNum * 2 <= n:
finalNum *= 2
return finalNum
# Driver code
if __name__ =="__main__":
N = 12
print( getFinalElement(N))
# This code is contributed
# by ChitraNayal
C#
// C# implementation of the approach
using System;
public class GFG{
// Function to return the final element
public static long getFinalElement(long n)
{
long finalNum;
for (finalNum = 2; finalNum * 2 <= n; finalNum *= 2)
;
return finalNum;
}
// Driver code
static public void Main (){
int N = 12;
Console.WriteLine(getFinalElement(N));
}
}
PHP
输出:
8
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。