📜  检入二进制数组,子数组表示的数字为奇数或偶数

📅  最后修改于: 2021-05-25 07:58:17             🧑  作者: Mango

给定一个数组,使其所有项均为0或1。您需要告诉子数组a [l..r]表示的数字为奇数或偶数
例子 :

Input : arr = {1, 1, 0, 1}
        l = 1, r = 3
Output : odd
        number represented by arr[l...r] is 
        101 which 5 in decimal form which is 
        odd

Input :  arr = {1, 1, 1, 1}
         l = 0, r = 3
Output : odd

这里要注意的重要一点是,二进制形式的所有奇数均以1作为最右边的位,所有偶数均以0作为其最右边的位。
原因很简单,除最右边的位以外,所有其他位均具有偶数,并且偶数之和始终为偶数。现在,最右边的位可以具有1或0的值,因为我们知道偶数+奇数=奇数,因此,当最右边的位为1时,数字为奇数,当最右边的位为0时,数字为偶数。
因此,要解决此问题,我们只需要检查a [r]是0还是1,并因此打印奇数或偶数即可

C++
// C++ program to find if a subarray
// is even or odd.
#include
using namespace std;
 
// prints if subarray is even or odd
void checkEVENodd (int arr[], int n, int l, int r)
{
    // if arr[r] = 1 print odd
    if (arr[r] == 1)
        cout << "odd" << endl;
 
    // if arr[r] = 0 print even
    else
        cout << "even" << endl;
}
 
// driver code
int main()
{
    int arr[] = {1, 1, 0, 1};
    int n = sizeof(arr)/sizeof(arr[0]);
    checkEVENodd (arr, n, 1, 3);
    return 0;
}


Java
// java program to find if a subarray
// is even or odd.
import java.io.*;
 
class GFG
{
    // prints if subarray is even or odd
    static void checkEVENodd (int arr[], int n, int l, int r)
    {
        // if arr[r] = 1 print odd
        if (arr[r] == 1)
            System.out.println( "odd") ;
     
        // if arr[r] = 0 print even
        else
            System.out.println ( "even") ;
    }
 
    // driver code
    public static void main (String[] args)
    {
        int arr[] = {1, 1, 0, 1};
        int n = arr.length;
        checkEVENodd (arr, n, 1, 3);
         
         
    }
}
 
// This article is contributed by vt_m.


Python3
# Python3 program to find if a
# subarray is even or odd.
 
# Prints if subarray is even or odd
def checkEVENodd (arr, n, l, r):
 
    # if arr[r] = 1 print odd
    if (arr[r] == 1):
        print("odd")
 
    # if arr[r] = 0 print even
    else:
        print("even")
 
# Driver code
arr = [1, 1, 0, 1]
n = len(arr)
checkEVENodd (arr, n, 1, 3)
 
# This code is contributed by Anant Agarwal.


C#
// C# program to find if a subarray
// is even or odd.
using System;
  
class GFG {
     
    // prints if subarray is even or odd
    static void checkEVENodd (int []arr,
                     int n, int l, int r)
    {
         
        // if arr[r] = 1 print odd
        if (arr[r] == 1)
            Console.WriteLine( "odd") ;
      
        // if arr[r] = 0 print even
        else
            Console.WriteLine( "even") ;
    }
  
    // driver code
    public static void Main()
    {
         
        int []arr = {1, 1, 0, 1};
        int n = arr.Length;
         
        checkEVENodd (arr, n, 1, 3);
    }
}
  
// This article is contributed by Anant Agarwal.


PHP


Javascript


输出 :

odd