Question :
An
integer array is said to be oddSpaced, if
the difference between the largest value and the smallest value is an odd
number. Write a function isOddSpaced(int[]
a) that
will return 1 if it isoddSpaced and 0
otherwise. If array has less than two elements, function will return 0. If you are programming in C or C++, the function signature is:
int isOddSpaced (int a[ ], int len) where len is the number of elements in the array.
Examples
Largest
value
|
Smallest value
|
Difference
|
Return
value
|
|
{100, 19, 131, 140}
|
140
|
19
|
140 -19 = 121
|
1
|
{200, 1, 151, 160}
|
200
|
1
|
200 -1 = 199
|
1
|
{200, 10, 151, 160}
|
200
|
10
|
200 -10 = 190
|
0
|
{100, 19, -131, -140}
|
100
|
-140
|
100 - (-140 ) = 240
|
0
|
{80, -56, 11, -81}
|
80
|
-81
|
-80 - 80 = -161
|
1
|
Solution:
public int isOddSpaced(int[] a)
{
int maxNumber = a[0], minNumber = a[0], rtnVal = 0;
if
(a.Length < 2)
{
rtnVal = 0;
}
else
{
for (int i = 0; i < a.Length; i++)
{
if
(maxNumber < a[i])
{
maxNumber = a[i];
}
}
for (int i = 0; i < a.Length; i++)
{
if (minNumber > a[i])
{
minNumber = a[i];
}
}
if((maxNumber-minNumber)%2!=0)
{
rtnVal = 1;
}
}
return rtnVal;
}
0 comments:
Post a Comment