Java > Recursion-1 > array11 (CodingBat Solution)

Problem:

Given an array of ints, compute recursively the number of times that the value 11 appears in the array. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array. The initial call will pass in index as 0.

array11({1, 2, 11}, 0) → 1
array11({11, 11}, 0) → 2
array11({1, 2, 3, 4}, 0) → 0


Solution:

public int array11(int[] nums, int index) {
  if (index >= nums.length) return 0;
  if (nums[index] == 11) return 1 + array11(nums,index+1);
  else return array11(nums,index+1);
}


5 comments :

  1. public int array11(int[] nums, int index) {
    if (index < nums.length) {
    return (nums[index] == 11 ? 1 : 0) + array11(nums, ++index);
    }
    return 0;
    }

    ReplyDelete
  2. public int array11(int[] nums, int index) {
    if (index >= nums.length)
    return 0;

    int count = nums[index] == 11 ? 1 : 0;

    return count + array11(nums, index+1);
    }

    ReplyDelete
  3. if ( index == nums.length ) return 0 ;
    if ( nums[index] == 11 ) return 1 + array11(nums,index+1);
    else return array11(nums,index+1);

    ReplyDelete
  4. public int array11(int[] nums, int index) {
    if(index>=nums.length)
    return 0;
    return nums[index]==11? array11(nums,index+1)+1 : array11(nums,index+1);
    }

    ReplyDelete

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