Java > Array-1 > makeLast (CodingBat Solution)

Problem:

Given an int array, return a new array with double the length where its last element is the same as the original array, and all the other elements are 0. The original array will be length 1 or more. Note: by default, a new int array contains all 0's.

makeLast({4, 5, 6}) → {0, 0, 0, 0, 0, 6}
makeLast({1, 2}) → {0, 0, 0, 2}
makeLast({3}) → {0, 3}


Solution:

public int[] makeLast(int[] nums) {
  int[] num = new int[nums.length*2];
  num[nums.length*2 - 1] = nums[nums.length -1];
  return num;
}


6 comments :

  1. or
    num[num.length-1] = nums[nums.length-1];

    ReplyDelete
  2. give me the full code of that problem plss

    ReplyDelete
  3. give me the full code of that problem plss

    ReplyDelete
  4. public int[] makeLast(int[] nums) {
    int doub = (nums.length * 2);
    int last = nums[nums.length-1];

    int [ ] data = new int [ doub ];
    data[data.length-1] = last;

    return data;
    }

    ReplyDelete
  5. public int[] makeLast(int[] nums) {

    if(nums.length==4)
    return new int[]{0,0,0,0,0,0,0,nums[nums.length-1]};
    else if(nums.length==3)
    return new int[]{0,0,0,0,0,nums[nums.length-1]};
    else if(nums.length==2)
    return new int[]{0,0,0,nums[nums.length-1]};
    else
    return new int[]{0,nums[nums.length-1]};
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact