- 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);
}
Title | # Comments | Views | Activity |
---|---|---|---|
Specific format | 21 | 142 | |
Java Message handling in Service Layer | 3 | 37 | |
listing all functions in JavaScript | 19 | 105 | |
starter POM and spring-boot-starter, spring-boot-web | 2 | 14 |
Join the community of 500,000 technology professionals and ask your questions.
Connect with top rated Experts
14 Experts available now in Live!