给定一个长度为n的数组。任务是检查给定的数组是否可以从奇数整数开始拆分为奇数个子段,并且子段的长度也必须为奇数。如果可能,请打印“ 1”,否则请打印“ 0”。
例子:
Input: arr[] = {1, 3, 1}
Output: 1
1, 3, 1, can be split into 3 sub-segments of length odd i.e. 1
with starting and ending elements as odd.
Input: arr[] = {1, 3, 1, 1}
Output: 0
方法:
在进行实际解决方案之前要考虑的几点:
- 通过将奇数次的集合的偶数相加而得出的集合的顺序始终是偶数,反之亦然。
- 通过将奇数集与奇数顺序相加而得出的集的顺序始终为奇数,反之亦然。
使用上述数论引理,可以使用以下建议的逻辑轻松计算给定问题的解决方案:
如果给定数组以奇数整数开始和结束,并且数组的大小也为奇数,则只有给定数组可以分解为奇数个子段,以奇数大小的奇数开头和结尾,否则不。
下面是上述方法的实现:
C++
// CPP to check whether given
// array is breakable or not
#include
using namespace std;
// Function to check
bool checkArray(int arr[], int n)
{
// Check the result by processing
// the first & last element and size
return (arr[0] % 2) && (arr[n - 1] % 2) && (n % 2);
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << (int)checkArray(arr, n);
return 0;
}
Java
// Java to check whether given
// array is breakable or not
class GFG
{
// Function to check
static int checkArray(int []arr, int n)
{
// Check the result by processing
// the first & last element and size
return ((arr[0] % 2) > 0 &&
(arr[n - 1] % 2) > 0 &&
(n % 2) > 0) ? 1 : 0;
}
// Driver code
public static void main(String[] args)
{
int []arr = { 1, 2, 3, 4, 5 };
int n = arr.length;
System.out.println(checkArray(arr, n));
}
}
// This code contributed by Rajput-Ji
Python3
# Python3 to check whether given
# array is breakable or not
# Function to check
def checkArray(arr, n):
# Check the result by processing
# the first & last element and size
return ((arr[0] % 2) and
(arr[n - 1] % 2) and (n % 2))
# Driver code
arr = [1, 2, 3, 4, 5 ]
n = len(arr);
if checkArray(arr, n):
print(1)
else:
print(0)
# This code is contributed
# by Mohit Kumar
C#
// C# to check whether given
// array is breakable or not
using System;
class GFG
{
// Function to check
static int checkArray(int []arr, int n)
{
// Check the result by processing
// the first & last element and size
return ((arr[0] % 2) > 0 &&
(arr[n - 1] % 2) > 0 &&
(n % 2) > 0) ? 1 : 0;
}
// Driver code
static void Main()
{
int []arr = { 1, 2, 3, 4, 5 };
int n = arr.Length;
Console.WriteLine(checkArray(arr, n));
}
}
// This code is contributed by mits
PHP
‘
输出:
1