题目
创建一个函数isDivisible(n, x, y)
,检查一个数字n
是否可被两个数字x
and y
整除。所有输入均为正数,非零数。
Example:
isDivisible(3,1,3)--> true // because 3 is divisible by 1 and 3
isDivisible(12,2,6)--> true // because 12 is divisible by 2 and 6
isDivisible(100,5,3)--> false // because 100 is not divisible by 3
isDivisible(12,7,5)--> false // because 12 is neither divisible by 7 nor 5
测试用例:
import static org.junit.Assert.*;
import java.util.Random;
import org.junit.Test;
public class DivisibleNbTests {
@Test
public void test1() {
assertEquals(true, DivisibleNb.isDivisible(12,4,3));
}
@Test
public void test2() {
assertEquals(false, DivisibleNb.isDivisible(3,3,4));
}
}
解题
My
public class DivisibleNb {
public static boolean isDivisible(long n, long x, long y) {
if (n % x == 0 && n % y == 0) {
return true;
}
return false;
}
}
Other
public class DivisibleNb {
public static Boolean isDivisible(long n, long x, long y) {
return (n%x ==0) && (n%y ==0);
}
}
后记
没想到我的答案还可以优化,看Other的答案。
网友评论