Issue
I am writing a small program to take an input array, nums
and create a new array that is double the size and returns the last number from the previous array as the last and only different number in the new array.
When I try to return this number using the nums.length - 1
formula to get the end of the array, it returns the number in the middle of the new array. Below is my program.
public int[] makeLast(int[] nums) {
int lengonewarr = nums.length;
int officiallength = lengonewarr * 2;
int [] makezero = new int [officiallength];
makezero [nums.length-1] = nums[nums.length-1];
return(makezero);
}
These are the outputs I should be making:
makeLast([4, 5, 6]) → [0, 0, 0, 0, 0, 6]
makeLast([1, 2]) → [0, 0, 0, 2]
makeLast([3]) → [0, 3]
But I instead get something like:
makeLast([1, 2, 3, 4]) → [0, 0, 0, 0, 0, 0, 0, 4] (My output) [0, 0, 0, 4, 0, 0, 0, 0]
makeLast([2, 4]) → [0, 0, 0, 4] (My output) [0, 4, 0, 0]
Any advice is greatly appreciated.
Solution
the array makezero
's length is officiallength
, not nums.length
, just replace the first nums.length
by makezero.length
or officiallength
.
makezero [makezero.length -1] = nums[nums.length-1];
BTW: It's better to name the variable with camelCase style, which will make the code more readable. Like makeZero
or officialLength
Answered By - seyoatda
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.