Friday, May 30, 2014

CodingBat > roundSum

For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper "public int round10(int num) {" and call it 3 times. Write the helper entirely below and at the same indent level as roundSum().

roundSum(16, 17, 18) → 60
roundSum(12, 13, 14) → 30
roundSum(6, 4, 4) → 10


Solution ::
 public int roundSum(int a, int b, int c) {
    return round10(a) + round10(b) + round10(c);
 }
 public int round10(int num) {
    int remainder = num % 10;
    num -= remainder;
    if (remainder >= 5) {
       num += 10;
    }
    return num;
 }

CodingBat > firstLast6

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({13, 6, 1, 2, 3}) → false

Solution ::
public class FirstLast6 {
 public static void main(String[] args) {
  FirstLast6 fl = new FirstLast6();
  int[] testArray = new int[] { 1, 2, 6 };
  System.out.print(fl.firstLast6(testArray));
 }

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