Tuesday 11 August 2015

Find final processed number

Given an array and an integer b, traverse the array and if the element in array is b, double b and continue traversal. In the end return value of b.

For example
For Input {2, 3, 4, 10, 8, 1, 16} b=2
Output: 32

public class ProcessArray {

 public static int getElement(int arr[], int ele) {
  for (int i = 0; i < arr.length; i++) {
   if (arr[i] == ele)
    ele = 2 * ele;
  }
  return ele;
 }
}


public class ProcessArrayTest {
 public static void main(String args[]){
  int arr[] = {2, 3, 4, 10, 8, 1, 16};
  System.out.println(ProcessArray.getElement(arr, 2));
 }
}


No comments:

Post a Comment