给定两个整数N和M ,任务是找到与N 边多边形的第M个顶点对角相对的顶点。
例子:
Input: N = 6, M = 2
Output: 5
Explanation:
It can be observed from the image above that the vertex opposite to vertex 5 is 2.
Input: N = 8, M = 5
Output: 1
Explanation:
It can be observed from the image above that the vertex opposite to vertex 8 is 1.
方法:解决给定问题需要考虑以下两种情况:
- 如果 M > N / 2:顶点将始终为M — (N / 2) 。
- 如果 M ≤ N / 2:顶点将始终为M + (N / 2) 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to return the
// required vertex
int getPosition(int N, int M)
{
// Case 1:
if (M > (N / 2)) {
return (M - (N / 2));
}
// Case 2:
return (M + (N / 2));
}
// Driver Code
int main()
{
int N = 8, M = 5;
cout << getPosition(N, M);
return 0;
}
Java
// Java program for
// the above approach
class GFG{
// Function to return the
// required vertex
static int getPosition(int N,
int M)
{
// Case 1:
if (M > (N / 2))
{
return (M - (N / 2));
}
// Case 2:
return (M + (N / 2));
}
// Driver Code
public static void main(String[] args)
{
int N = 8, M = 5;
System.out.print(getPosition(N, M));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program for the
# above approach
# Function to return the
# required vertex
def getPosition(N, M):
# Case 1:
if (M > (N // 2)):
return (M - (N // 2))
# Case 2:
return (M + (N // 2))
# Driver Code
N = 8
M = 5
print(getPosition(N, M))
# This code is contributed by code_hunt
C#
// C# program for the above approach
using System;
class GFG{
// Function to return the
// required vertex
static int getPosition(int N, int M)
{
// Case 1:
if (M > (N / 2))
{
return (M - (N / 2));
}
// Case 2:
return (M + (N / 2));
}
// Driver Code
public static void Main(String[] args)
{
int N = 8, M = 5;
Console.Write(getPosition(N, M));
}
}
// This code is contributed by Amit Katiyar
Javascript
输出:
1
时间复杂度: O(1)
辅助空间: O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。