id/email
password
forgot password | create account
about | help | code help+videos | done | prefs
CodingBat code practice

 

srp4379@lausd.net 1-arraybasics > getSmallest2_DifferentLengthsA
prev  |  next  |  chance

public int getSmallest2_DifferentLengthsA(int[] nums)

Given an int[] array whose length is anywhere from 0-2,
i.e. it has either zero, one or two elements,
return the smallest value.

This problem requires that you check the length of the array
before you try to access an element, to make sure that it exists.

Therefore, you will have 3 different if statements - 3 different sections -
one for each of the possible array lengths.

public int getSmallest2_DifferentLengths(int[] nums) {
  int smallest = 0; // default if length == 0 (the empty array)
  int len = nums.length;

  if (len == 0) {
    smallest = 0; // NOT NECESSARY, because length == 0 is the default
  }

  if (len == 1) {
    smallest = nums[0];
  }

  if (len == 2) {
    smallest = Math.min( nums[0], nums[1] );
  }

  return smallest;
}
Note that the three sections are mutually exclusive.
That means:

An empty array will only execute the statement(s) within the
block governed by if (len == 0)

An array with a single element will only execute the statement(s)
within the block governed by if (len == 1)

An array with 2 elements will only execute the statement(s)
within the block governed by if (len == 2)

getSmallest2_DifferentLengthsA([]) → 0
getSmallest2_DifferentLengthsA([5]) → 5
getSmallest2_DifferentLengthsA([3, 6]) → 3

...Save, Compile, Run (ctrl-enter)

public int getSmallest2_DifferentLengthsA(int[] nums) { }

Editor font size %:
Shorter output


Forget It! -- delete my code for this problem

Progress graphs:
 Your progress graph for this problem
 Random user progress graph for this problem
 Random Epic Progress Graph

Java Help

Misc Code Practice

Difficulty: 1

Copyright Nick Parlante 2017 - privacy