Check in binary array the number represented by a subarray is odd or even
Last Updated :
19 Sep, 2023
Given an array such that all its terms is either 0 or 1.You need to tell the number represented by a subarray a[l..r] is odd or even
Examples :
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
The important point to note here is all the odd numbers in binary form have 1 as their rightmost bit and all even numbers have 0 as their rightmost bit.
The reason is simple all other bits other than the rightmost bit have even values and the sum of even numbers is always even. Now the rightmost bit can have a value of either 1 or 0 as we know even + odd = odd so when the rightmost bit is 1 the number is odd and when it is 0 the number is even.
So to solve this problem we have to just check if a[r] is 0 or 1 and accordingly print odd or even
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
void checkEVENodd ( int arr[], int n, int l, int r)
{
if (arr[r] == 1)
cout << "odd" << endl;
else
cout << "even" << endl;
}
int main()
{
int arr[] = {1, 1, 0, 1};
int n = sizeof (arr)/ sizeof (arr[0]);
checkEVENodd (arr, n, 1, 3);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static void checkEVENodd ( int arr[], int n, int l, int r)
{
if (arr[r] == 1 )
System.out.println( "odd" ) ;
else
System.out.println ( "even" ) ;
}
public static void main (String[] args)
{
int arr[] = { 1 , 1 , 0 , 1 };
int n = arr.length;
checkEVENodd (arr, n, 1 , 3 );
}
}
|
Python3
def checkEVENodd (arr, n, l, r):
if (arr[r] = = 1 ):
print ( "odd" )
else :
print ( "even" )
arr = [ 1 , 1 , 0 , 1 ]
n = len (arr)
checkEVENodd (arr, n, 1 , 3 )
|
C#
using System;
class GFG {
static void checkEVENodd ( int []arr,
int n, int l, int r)
{
if (arr[r] == 1)
Console.WriteLine( "odd" ) ;
else
Console.WriteLine( "even" ) ;
}
public static void Main()
{
int []arr = {1, 1, 0, 1};
int n = arr.Length;
checkEVENodd (arr, n, 1, 3);
}
}
|
PHP
<?php
function checkEVENodd ( $arr , $n , $l , $r )
{
if ( $arr [ $r ] == 1)
echo "odd" , "\n" ;
else
echo "even" , "\n" ;
}
$arr = array (1, 1, 0, 1);
$n = sizeof( $arr );
checkEVENodd ( $arr , $n , 1, 3);
?>
|
Javascript
<script>
function checkEVENodd (arr, n, l, r)
{
if (arr[r] == 1)
document.write( "odd" ) ;
else
document.write( "even" ) ;
}
let arr = [1, 1, 0, 1];
let n = arr.length;
checkEVENodd (arr, n, 1, 3);
</script>
|
Time Complexity : O(1)
Space Complexity : O(1)
This article is contributed by Ayush Jha.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...