Java > Array-1 > sameFirstLast (CodingBat Solution)

Problem:

Given an array of ints, return true if the array is length 1 or more, and the first element and the last element are equal.

sameFirstLast({1, 2, 3}) → false
sameFirstLast({1, 2, 3, 1}) → true
sameFirstLast({1, 2, 1}) → true


Solution:

public boolean sameFirstLast(int[] nums) {
  if (nums.length >= 1 && nums[0] == nums[nums.length-1])
    return true;
  else 
    return false;
}


8 comments :

  1. This comment has been removed by the author.

    ReplyDelete
  2. public boolean sameFirstLast(int[] nums) {
    if (nums.length == 0 || nums[0] != nums[nums.length - 1]){
    return false;
    }
    return true;
    }

    ReplyDelete
  3. public boolean sameFirstLast(int[] nums) {
    return (nums.length != 0) && (nums[0] == nums[nums.length - 1]);
    }

    ReplyDelete
  4. public boolean sameFirstLast(int[] nums) {
    if (nums.length==0)return false;
    if (nums[0]==nums[nums.length-1]) return true ;
    else return false ;
    }

    ReplyDelete
  5. public boolean sameFirstLast(int[] nums)
    {


    if((nums.length)!=0)
    {
    if(nums[0]==nums[nums.length-1])
    return true;
    }




    return false;
    }

    ReplyDelete

  6. if (nums.length = 1 && nums[0] == nums[nums.length -1]){
    return true;

    }else{
    return false;
    }


    }

    ReplyDelete
    Replies
    1. public boolean sameFirstLast(int[] nums) {
      if (nums.length == 1 && nums[0] == nums[nums.length -1]){
      return true;

      }else{
      return false;
      }


      }

      Delete

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