Interview Questions

198. Given eight 8s: 8 8 8 8 8 8 8 8 .......

Microsoft Interview Questions and Answers


(Continued from previous question...)

198. Given eight 8s: 8 8 8 8 8 8 8 8 .......

Question:
Given eight 8s: 8 8 8 8 8 8 8 8, add any number of "+"s between the 8's to make the sum equals 1000.


maybe an answer:


int[] arr = new int[8];
int index = 0;


void calculateEightEights(int target, int numEightLeft)
{
int prevResult = 0, curResult = 0;
for (int i=1; i<=numEightLeft; i++)
{
curResult = (curResult * 10) + 8
; if (curResult > target)
{
arr[index++] = prevResult;
calculateEightEights(target - prevResult, numEightLeft - i + 1);
}
prevResult = curResult;
}
}

To invoke the method: calculateEightEights(1000,8);

(Continued on next question...)

Other Interview Questions