Skip to content

1.11 Abs different of array

Farrukh Ahmad edited this page Dec 18, 2015 · 1 revision

For instance

  • 5 is abs of (2 - (-3))
  • 1 is abs of (-3 - (-2))
  • 8 is abs of (-2 - 6)
  • 3 is abs of (6-9)
  • 9 is abs of (9-18)

hence [2, -3, -2, 6, 9, 18] abs different is 51839, but if first element of array -ve resulted number will be also -ve. ie. [-1, 5, 8, 17, 15] abs different is -6392

public class AbsoluteDifference {

public static void main(String[] args) {
	int a[] = {-1, 5, 8, 17, 15};
	System.out.println(makeAbs(a));
}


static int makeAbs(int a[]){
	double result = 0;
	for(int i= 0; i<a.length-1; i++){
		int abs = Math.abs(a[i]-a[i+1]);
	double digitValue = abs * (Math.pow(10, a.length-2-i));
		
		result = result + digitValue;
	}
	return (int)(a[0] < 0 ? result*-1 : result);
}
}

Clone this wiki locally