Created
August 22, 2017 00:10
-
-
Save marlonlom/bb4805196552e580c320e8677a3ccee3 to your computer and use it in GitHub Desktop.
MiddleNumber.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MiddleNumber | |
{ | |
public static void main(String[] args) | |
{ | |
MiddleNumber myObject = new MiddleNumber(); | |
int[] numberz = {1,2,4,60,8,20}; | |
int[] resultz= myObject.makeMiddle(numberz); | |
System.out.print("myObject.makeMiddle: "+resultz[0]); | |
} | |
public int[] makeMiddle(int[] nums) { | |
int[] a; | |
if (nums.length %2 == 0) { | |
// even-length array (two middle elements) | |
a = new int[2]; | |
a[0] = nums[(nums.length/2) - 1]; | |
a[1] = nums[nums.length/2]; | |
} else { | |
// odd-length array (only one middle element) | |
a = new int[1]; | |
a[0] = nums[nums.length/2]; | |
} | |
return a; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment