Sunday, January 16, 2011

Java Bat : Array 1 : FirstLast6

In Array 1 section, these are simple Array based problems in which there is no use of loops to solve the problems.

First Last 6 Problem : Given an array of ints, return true if 6 appears as either the first or last element in the array. The array will be length 1 or more.

firstLast6({1, 2, 6}) → true
firstLast6({6, 1, 2, 3}) → true
firstLast6({3, 2, 1}) → false

In this problem an array of ints is passed to a method firstLast6 and if 6 appears as either the first or last element in the array the firstLast6 method will return true else it will return false.

To check weather first and last element is 6 or not.


                    nums[0]==6 || nums[nums.length-1]==6


So the Answer for this Java Bat Problem:


           public boolean firstLast6( int[] nums ) {
                   
                        if ( nums[0]==6 || nums[nums.length-1]==6 ){
                                      return true;
                        }
                        else{
                                     return false;

                        }
          }

1 comment: