What are the business impacts of how well businesses communicate during an IT incident? Targeting, speed, and transparency all matter. Find out more in this infographic.
Become a Premium Member and unlock a new, free course in leading technologies each month.
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
Add your voice to the tech community where 5M+ people just like you are talking about what matters.
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 |
---|---|---|---|
DTD and JAVA versions | 1 | 55 | |
Oracle programming for starter | 14 | 75 | |
Best laptop programming computer for Windows development | 14 | 87 | |
Selenium WebElement Login button findElement | 9 | 17 |
Join the community of 500,000 technology professionals and ask your questions.