The Java Learning Project

I started learning Java programming and found a perfect website for practicing: Codingbat.com. CodingBat is a free site of live coding problems to build coding skill in Java and Python. CodingBat is a project by Nick Parlante, a computer science lecturer at Stanford.

I will upload my solutions here.

When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return true if the party with the given values is successful, or false otherwise.

cigarParty(30, false) → false
cigarParty(50, false) → true
cigarParty(70, true) → true

1
2
3
public boolean cigarParty(int cigars, boolean isWeekend) {
  return (((cigars>=40 && cigars<=60) && !isWeekend) || (cigars>=40 && isWeekend));
}

Given an array of ints of odd length, look at the first, last, and middle values in the array and return the largest. The array length will be a least 1.

maxTriple([1, 2, 3]) → 3
maxTriple([1, 5, 3]) → 5
maxTriple([5, 2, 3]) → 5

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public int maxTriple(int[] nums) {
  int max=0;
  int first=nums[0];
  int last=nums[nums.length-1];
  int mid=nums[nums.length/2];
  if ((first>last) && (first>mid)){
    max=first;
  }else if ((last>first) && (last>mid)) {
    max=last;
  }else{
    max=mid;
  }
  return max;
}

Given an array of ints of odd length, return a new array length 3 containing the elements from the middle of the array. The array length will be at least 3.

midThree([1, 2, 3, 4, 5]) → [2, 3, 4]
midThree([8, 6, 7, 5, 3, 0, 9]) → [7, 5, 3]
midThree([1, 2, 3]) → [1, 2, 3]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public int[] midThree(int[] nums) {
  int[] result = new int[3];
  if (nums.length>3){
     result[0]=nums[(nums.length/2)-1];
     result[1]=nums[(nums.length/2)];
     result[2]=nums[(nums.length/2)+1];
  }else{
    result=nums;
  }return result;
}

Keresés

Ajánló