AP计算机教程5-8:自我除数A
A positive integer is called a “self-divisor” if every decimal digit of the number is a divisor of the number, that is, the number is evenly divisible by each and every one of its digits. For example, the number 128 is a self- divisor because it is evenly divisible by 1, 2, and 8. However, 26 is not a self-divisor because it is not evenly divisible by the digit 6. Note that 0 is not considered to be a divisor of any number, so any number containing a 0 digit is NOT a self-divisor. There are infinitely many self-divisors.
Finish writing method isSelfDivisor below, which takes a positive integer as its parameter. This method returns true if the number is a self-divisor; otherwise, it returns false. The main method includes tests to check if this method is working correctly.
public class SelfDivisor { /** @param number the number to be tested * Precondition: number > 0 * @return true if every decimal digit of * number is a divisor of number; * false otherwise */ public static boolean isSelfDivisor(int number) { // part A } /****************/ public static void main (String[] args) { System.out.println("128: " + isSelfDivisor(128)); System.out.println("26: " + isSelfDivisor(26)); System.out.println("120: " + isSelfDivisor(120)); System.out.println("102: " + isSelfDivisor(102)); } }
如何解题
首先我们试着手算一下。题目中明确method对128
应该返回true
,26
应该返回false
,任何带有0
的数字也应该返回false
。
为检查128
是否是一个自我除数,我们将它分别除以8
、2
和1
,如果余数均为0
即均被整除的话,method应该返回true
。
public class Test { public static void main(String[] args) { System.out.println(128 % 8); System.out.println(128 % 2); System.out.println(128 % 1); } }
为检查26
是否是一个自我除数,我们将它除以6
,发现余数大于0
。因而其不是自我除数,method返回false
。
public class Test { public static void main(String[] args) { System.out.println(26 % 6); } }
任何带有0
的数字也应该返回false
,意味着当前数字是0
时method直接以false
为结果结束循环。120
和102
应均返回false
。
综上,我们应该每次循环一位数字,测试其如果是0
的话即返回false
。如不为0
,则测试参数能否被数字所整除,不能的话即返回false
。在循环完所有数字之后没有问题的情况下则返回true
。
我们又如何能循环整数的每位数字呢?我们可以使用x % 10
来得到最右边一位数字,以及使用x / 10
来将最右边一位数字移除。取模运算符%
还可以用来测试整除。运行以下示例以更深入的了解%
和/
是如何工作的。
public class Test { public static void main(String[] args) { System.out.println(128 % 10); System.out.println(128 / 10); System.out.println(12 % 10); System.out.println(12 / 10); } }
0:00
Which loop should you use to loop through all the digits of the number?
while
。我们需要循环遍历method给定参数中的所有数字。例如,对128
而言循环的第一轮我们想测试8
,循环的第二轮测试2
,最后一轮测试1
。我们可以使用x % 10
来得到最右边一位数字,以及使用x / 10
来移除它。我们需要一个局域变量来存储参数的一个副本,因为在每次循环中这个副本都要被移除一位。在循环中,我们必须先测试数字是否为0
(利用短路求解来防止除零的错误),再测试整除。循环将在所有数字被移除后结束,此时n = 0
。
What should you use as the test in the while loop?
0
时一直继续循环,不然会遗漏最左边的一位。以下是本题的参考答案。
public static boolean isSelfDivisor(int number) { int n = number; while (n > 0) { int digit = n % 10; if (digit == 0 || number % digit != 0) { return false; } n /= 10; } return true; }
0 条评论