I applied for a job and was asked to do a Codility test. The test was the following:
Return the number of integers within the range [A..B] that are divisible by K.
Args:
Time complexity must be O(1).
I know my solution isn't O(1), I couldn't come up with a better solution than this. Can anyone enlighten me?
BTW, it's in C# so 'int' is large enough to hold 2000000000.
public int solution(int A, int B, int K)
{
int i=0;
for(int x=A;x<=B;x++)
{
if((x % K) == 0)
i++;
}
return i;
}
Here's my solution in Java, score 100%
public int solution(int A, int B, int K) {
int count = (B/K - A/K) + (A%K == 0 ? 1 : 0);
return count;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With