Mincong Huang - 10 months ago 39

Java Question

There're a construction site and there're works to do. And we need certain number of workers to do them. Each worker has the same work capacity and they can't handle more than that limit. So for a given number of works, the number of workers required is :

- If the is an integer multiple of
`works`

, then`workerCapacity`

will be a simple division of`workers`

.`works / workerCapacity`

- If the is not an integer multiple of
`works`

, then after the division, we need to increment one. E.g. if capacity = 10, 100 works need 10 workers but 101 works need 11 workers.`workerCapacity`

Here's my implementation:

`public int getNumWorkers(int works) {`

int workers = works / workerCapacity;

if (works % workerCapacity != 0) {

workers++;

}

return workers;

}

My question is: can we simplify the lines 2-5 into only one line ?

Answer

Yes, you can. Add `workerCapacity-1`

before dividing it out, like this:

```
return (works+workerCapacity-1) / workerCapacity;
```

If `workerCapacity`

divides `works`

evenly (i.e. `works % workerCapacity == 0`

) adding `workerCapacity-1`

will be too little to change the answer. If the remainder is above zero, adding `workerCapacity-1`

will increase the result of division by one.