- if the index is greater than 0 and nums[index] is equal to 10 times nums[index-1] then stop with success.
- proceed recursion by calling array220 passing the array and the index incremented by 1 and return the result.
Sara
Recursion-1 > array220
prev | next | chance
Given an array of ints, compute recursively if the array contains somewhere a value followed in the array by that value times 10. 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.
array220([1, 2, 20], 0) → true
array220([3, 30], 0) → true
array220([3], 0) → false
array220([1, 2, 20], 0) → true
array220([3, 30], 0) → true
array220([3], 0) → false
so 1 *10 is 10 are we expected to see 10 in rest of elements
the challenge is to find a pair of consecutive numbers where (left * 10 == right).
public boolean array220(int[] nums, int index) {
if(index>nums.length-2){
return false;
}
if(nums[index+1]==nums[index]*10){
return true;
}
else{
return array220(nums,index+1);
}
}
public boolean array220(int[] nums, int index) {
if(index>nums.length-2){
return false;
}
if(nums[index]*10==nums[index+1]){
return true;
}
else{
return array220(nums,index+1);
}
}
/*- recursion stops with false if the index is greater or equal to array length.
- if the index is greater than 0 and nums[index] is equal to 10 times nums[index-1]
then stop with success.
- proceed recursion by calling array220 passing the array and the index incremented
by 1 and return the result.
*/
any improvements or alternate approaches?
public boolean array220(int[] nums, int index) {
if(index>=nums.length){
return false;
}
if(index > 0 && nums[index-1]*10==nums[index]){
return true;
}
return array220(nums,index+1);
}
If you are experiencing a similar issue, please ask a related question
Title | # Comments | Views | Activity |
---|---|---|---|
Java - Why doesn't this JFrame work | 3 | 43 | |
C# Error - Add Failed | 12 | 78 | |
map related example | 6 | 36 | |
tomcat administrtor | 12 | 29 |
Join the community of 500,000 technology professionals and ask your questions.
Connect with top rated Experts
14 Experts available now in Live!