3.2 CountDiv

来源:互联网 发布:视频去码软件 编辑:程序博客网 时间:2024/04/28 09:41

Write a function:
class Solution { public int solution(int A, int B, int K); }
that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:
{ i : A ≤ i ≤ B, i mod K = 0 }
For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10.
Assume that:
A and B are integers within the range [0..2,000,000,000];
K is an integer within the range [1..2,000,000,000];
A ≤ B.
Complexity:
expected worst-case time complexity is O(1);
expected worst-case space complexity is O(1).

Solution

class Solution {    public int solution(int A, int B, int K) {        // write your code in Java SE 8        if(A>=B) return 0;        int countB = B/K;        int countA = A/K;        if(A%K==0) return countB-countA+1;        else return countB-countA;    }}

点评

从0到B有countB个满足条件,0到A有countA个。考虑边界条件如果A可以整除就加1.
网站的测试case有问题啊,A = 10, B = 10, K=5,结果是1没问题啊。K=7,20本算法也能得出正确结果0
minimal
A, B in {0,1}, got 0 expected 1
extreme_ifempty
A = 10, B = 10, K in {5,7,20} got 0 expected 1
big_values4
A, B, K in {1,MAXINT} got 0 expected 1

0 0
原创粉丝点击