Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

I had an interesting job interview experience a while back. The question started really easy: Q1: We have a bag containing numbers 1, 2, 3, …, 100. Each number appears exactly once, so there are 100 numbers. Now one number is randomly picked out of the bag. Find the missing number. I’ve heard this interview … Read more

Fastest way to determine if an integer’s square root is an integer

I’m looking for the fastest way to determine if a long value is a perfect square (i.e. its square root is another integer): I’ve done it the easy way, by using the built-in Math.sqrt() function, but I’m wondering if there is a way to do it faster by restricting yourself to integer-only domain. Maintaining a … Read more

How to round up to the next integer?

No, Math.ceil() won’t work on its own because the problem occurs earlier. a and b are both integers, so dividing them evaluates to an integer which is the floor of the actual result of the division. For a = 3 and b = 2, the result is 1. The ceiling of one is also one – hence you won’t get the desired result. You must … Read more

Division of integers in Java

Converting the output is too late; the calculation has already taken place in integer arithmetic. You need to convert the inputs to double: System.out.println((double)completed/(double)total); Note that you don’t actually need to convert both of the inputs. So long as one of them is double, the other will be implicitly converted. But I prefer to do both, for symmetry.